繁体   English   中英

Python 从列表和元组创建字典

[英]Python creating dictionary from list and tuple

当我像这样遍历字典时:

dict2={
'Joe':('Caucasian','Male', 35, 7.5),
'Kevin':('Black','Male', 55, 9.5),
 More tuples here like the one above
}

数据更大,但在这里无关紧要。

我想要完成的是使用来自 tuples 的信息创建一个新字典 像这样:

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() 这样的内置 function 或类似的东西。 我想硬编码解决方案

@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)

Output:

[{'ethnicity': 'Caucasian',
  'gender': 'Male',
  'name': 'Joe',
  'score': 7.5,
  'voter_age': 35},
 {'ethnicity': 'Black',
  'gender': 'Male',
  'name': 'Kevin',
  'score': 9.5,
  'voter_age': 55}]

字典键必须是唯一的。 您只是在循环中的每个循环中覆盖您的 dict 。 这就是dicts的工作方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM