import csv
def partytoyear():
party_in_power = {}
with open("presidents.txt") as f:
reader = csv.reader(f)
for row in reader:
party = row[1]
for year in row[2:]:
party_in_power[year] = party
print(party_in_power)
return party_in_power
partytoyear()
def statistics():
with open("BLS_private.csv") as f:
statistics = {}
reader = csv.DictReader(f)
for row in reader:
statistics = row
print(statistics)
return statistics
statistics()
这两个函数返回两个字典。
以下是第一本词典的示例:
'Democrat', '1981': 'Republican', '1982': 'Republican', '1983'
第二本词典的样本:
'2012', '110470', '110724', '110871', '110956', '111072', '111135', '111298', '111432', '111560', '111744'
第一本词典将年份和政党联系在一起。下一本字典将年份与工作统计相关联。
我需要将这两个字典结合起来,这样我才能在字典中将聚会与工作统计信息结合在一起。
我希望字典是这样的:
'Democrat, '2012','110470', '110724', '110871', '110956', '111072', '111135', '111298', '111432', '111560', '111744'
我将如何去做?我已经看过update()的语法,但这对我的程序不起作用
答案 0 :(得分:0)
在该庄园中,您无法在python中使用字典,这在语法上是错误的,但是您可以将每个值都作为一个集合(例如列表)。这是一种使用字典查询来完成的理解:
first_dict = {'Democrat': '1981': 'Republican': '1982': 'Republican': '1983', ...}
second_dict = {'2012': ['110470', '110724', '110871', '110956', '111072', '111135', '111298', '111432', '111560', '111744'], ...}
result = {party: [year, *second_dict[year] for party, year in first_dict.items()}
伪结果字典结构:
{'Party Name': [year, stats, ...], ...}