name_list=['Tomas', 'Mina', 'John', 'Amy']
gender_list=['Male', 'Female', 'Male', 'Female']
How to create a dictionary variable that contains name:gender pairs using the name_list and gender list?
I have to use 'for'
name_list=['Tomas', 'Mina', 'John', 'Amy']
gender_list=['Male', 'Female', 'Male', 'Female']
How to create a dictionary variable that contains name:gender pairs using the name_list and gender list?
I have to use 'for'
No need to use for
.
Use zip
to get a pairs of (key, value); then pass it to dict
to get a mapping of those pairs:
>>> name_list=['Tomas', 'Mina', 'John', 'Amy']
>>> gender_list=['Male', 'Female', 'Male', 'Female']
>>> dict(zip(name_list, gender_list))
{'Amy': 'Female', 'Tomas': 'Male', 'John': 'Male', 'Mina': 'Female'}
Alternatively, you can use dictionary comprehension:
>>> {name: gender for name, gender in zip(name_list, gender_list)}
{'Amy': 'Female', 'Tomas': 'Male', 'John': 'Male', 'Mina': 'Female'}