Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a dict using zip

Tags:

python

I have a list of names:

['john smith', 'sally jones', 'bob jones']

I want to build a dict in the following format:

{'john smith': [], 'sally jones': [], 'bob jones': []}

This is what happens when I try using zip

zip((all_crew_names, [[] for item in all_crew_names]))
[(['john smith', 'sally jones', 'bob jones'],), ([[], [], []],)]

What am I doing incorrectly here, and how would I properly zip this up?

like image 724
David542 Avatar asked Sep 09 '26 15:09

David542


2 Answers

The easiest solution here is a dictionary comprehension:

names = ['john smith', 'sally jones', 'bob jones']
d = {name: [] for name in names}

Note that it might be tempting to use dict.fromkeys(names, []), but this would result in the same list being used for all keys.

like image 99
Sven Marnach Avatar answered Sep 11 '26 04:09

Sven Marnach


You don't need zip.

{name: [] for name in all_crew_names}

In older versions of Python there was no such dictionary comprehension, so the following code can be used:

dict((name, []) for name in all_crew_names)
like image 30
Oleh Prypin Avatar answered Sep 11 '26 06:09

Oleh Prypin