简体   繁体   中英

create dictionary from two lists

I'm new to this and I'm having some issues finishing up a part of my homework. basically I have 2 lists:

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]

What I'm trying to achieve is a dictionary that looks like that:

{'Jerry': {'age': 27},
 'Fernando': {'age': 27},
 # ...
 'Billy': {'age': 24},
}

I used tuples to display it like this [('Jerry', 27), ('Fernando', 27), ..., ('Billy', 24)] but I can't figure out how to display it in a dictionary with each key, value on a new line.

Use a dictionary comprehension:

{name: {'age': age} for name, age in zip(names, ages)}

Demo:

>>> 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}}

您可以将其压缩:

dict(zip(names, ({'age': a} for a in ages)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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