我是新手,我在完成一部分作业时遇到了一些问题。基本上我有2个列表:
names = ["Jerry", "Fernando", "Radu", "Juan", "Brie", "Dani", "Fallon", "Nina", "Max", "Mike", "Johnny", "Saul", "Simon", "Billy"]
ages = [27, 27, 23, 27, 27, 23, 33, 32, 25, 32, 26, 26, 29, 24]
我想要实现的是一本看起来像这样的词典:
{'Jerry': {'age': 27},
'Fernando': {'age': 27},
# ...
'Billy': {'age': 24},
}
我使用元组来显示它[('Jerry', 27), ('Fernando', 27), ..., ('Billy', 24)]
,但我无法弄清楚如何在字典中显示它,每个键值都在新行上。
答案 0 :(得分:4)
使用词典理解:
{name: {'age': age} for name, age in zip(names, ages)}
演示:
>>> from pprint import pprint
>>> names = ["Jerry", "Fernando", "Radu", "Juan", "Brie", "Dani", "Fallon", "Nina", "Max", "Mike", "Johnny", "Saul", "Simon", "Billy"]
>>> ages = [27, 27, 23, 27, 27, 23, 33, 32, 25, 32, 26, 26, 29, 24]
>>> {name: {'age': age} for name, age in zip(names, ages)}
{'Mike': {'age': 32}, 'Simon': {'age': 29}, 'Johnny': {'age': 26}, 'Max': {'age': 25}, 'Juan': {'age': 27}, 'Jerry': {'age': 27}, 'Fernando': {'age': 27}, 'Nina': {'age': 32}, 'Billy': {'age': 24}, 'Radu': {'age': 23}, 'Dani': {'age': 23}, 'Fallon': {'age': 33}, 'Brie': {'age': 27}, 'Saul': {'age': 26}}
>>> pprint(_)
{'Billy': {'age': 24},
'Brie': {'age': 27},
'Dani': {'age': 23},
'Fallon': {'age': 33},
'Fernando': {'age': 27},
'Jerry': {'age': 27},
'Johnny': {'age': 26},
'Juan': {'age': 27},
'Max': {'age': 25},
'Mike': {'age': 32},
'Nina': {'age': 32},
'Radu': {'age': 23},
'Saul': {'age': 26},
'Simon': {'age': 29}}
答案 1 :(得分:1)
你可以压缩它:
dict(zip(names, ({'age': a} for a in ages)))