当我像这样迭代字典时:
dict2={
'Joe':('Caucasian','Male', 35, 7.5),
'Kevin':('Black','Male', 55, 9.5),
More tuples here like the one above
}
数据更大,但在这里无关紧要。
我想要完成的是用元组中的信息创建一个新字典。像这样:
dict_i_want = {
"Name": Joe,
"Ethiniticy": "Caucasian",
"Gender":"Male",
"Voter_age": 35,
"Score": 7.5
}
这是我的代码:
dict_i_want = {}
for k,v in dict2.items():
dict_i_want["Name"] = k
dict_i_want['Ethiniticy'] = v[0]
dict_i_want['Gender'] = v[1]
dict_i_want['Voter_age'] = v[2]
dict_i_want['Score'] = v[3]
但是当我这样做时
print(dict_i_want)
{'Name': 'Kevin', 'Ethiniticy': 'Black', 'Gender': 'Male', 'Voter_age': 55, 'Score': 9.5}
结果只是我在 mydict2 中的最后一个元组。没有所有的元组。 如果我有循环,我做错了什么?
PS:我不想在这里使用任何模块或导入任何东西。没有像 zip() 之类的内置函数。我想对解决方案进行硬编码
答案 0 :(得分:3)
@ForceBru 回答了您的问题 - 最好的选择是字典列表,除非您想为每个子字典创建一个具有唯一键的字典。使用列表方法,您可以执行以下操作:
示例:
from pprint import pprint
dict2 = {
'Joe': ('Caucasian', 'Male', 35, 7.5),
'Kevin': ('Black', 'Male', 55, 9.5),
}
dicts_i_want = [
{"name": name, "ethnicity": ethnicity, "gender": gender, "voter_age": voter_age, "score": score}
for name, (ethnicity, gender, voter_age, score) in dict2.items()
]
pprint(dicts_i_want)
输出:
[{'ethnicity': 'Caucasian',
'gender': 'Male',
'name': 'Joe',
'score': 7.5,
'voter_age': 35},
{'ethnicity': 'Black',
'gender': 'Male',
'name': 'Kevin',
'score': 9.5,
'voter_age': 55}]
答案 1 :(得分:1)
字典键必须是唯一的。你只是在循环中的每个周期覆盖你的字典。这就是 dicts 的工作原理。