简体   繁体   中英

Creating a dictionary with a list of names

I have this list of names: [Frank, Sam, Kevin, Jack]

Is it possible to create a dictionary using the names in the list to create something like this?

'Frank' : {'Sam': 0, 'Kevin': 0, 'Jack': 0},
 'Sam' : {'Frank': 0, 'Kevin': 0, 'Jack': 0},
 'Kevin' : {'Frank': 0, 'Sam': 0, 'Jack': 0}
 'Jack' : {'Frank': 0, 'Sam': 0,  'Kevin': 0}

I want to know if it's possible to iterate through the list, pick the first name and then create a dictionary with it, with the other members in the list as keys and 0 as the default value. And then repeat it for the other elements in the list as well.

I was thinking of using something like this.

my_dynamic_vars = dict()
my_dynamic_vars.update({string: dict()})

Any help would be much appreciated.

You can use nested dictionary comprehensions :

>>> lst = ['Frank', 'Sam', 'Kevin', 'Jack']
>>> dct = {x:{y:0 for y in lst if y != x} for x in lst}
>>> dct
{'Frank': {'Kevin': 0, 'Sam': 0, 'Jack': 0}, 'Kevin': {'Frank': 0, 'Jack': 0, 'Sam': 0}, 'Sam': {'Frank': 0, 'Jack': 0, 'Kevin': 0}, 'Jack': {'Frank': 0, 'Kevin': 0, 'Sam': 0}}
>>>
>>> # Just to demonstrate
>>> from pprint import pprint
>>> pprint(dct)
{'Frank': {'Jack': 0, 'Kevin': 0, 'Sam': 0},
 'Jack': {'Frank': 0, 'Kevin': 0, 'Sam': 0},
 'Kevin': {'Frank': 0, 'Jack': 0, 'Sam': 0},
 'Sam': {'Frank': 0, 'Jack': 0, 'Kevin': 0}}
>>>

ummm

d= {}
names = ["Frank","Sam","Kevin","Jack"]
for name in names:
    d[name] = dict.fromkeys(set(names).difference([name]),0)

print d

is probably how I would do it ..

names = ['Frank', 'Sam', 'Kevin', 'Jack']
d = dict.fromkeys(names, 0)

names_dict = {}

for name in names:
    temp = d.copy()
    del temp[name]
    names_dict.update([(name, temp)])

output:

>>> for d in names_dict:
>>>     print d    
'Frank': {'Jack': 0, 'Kevin': 0, 'Sam': 0}
'Sam': {'Frank': 0, 'Jack': 0, 'Kevin': 0}
'Kevin': {'Frank': 0, 'Jack': 0, 'Sam': 0}
'Jack': {'Frank': 0, 'Kevin': 0, 'Sam': 0}
names = ['Frank', 'Sam', 'Kevin', 'Jack']
d = {name: dict.fromkeys([x for x in names if x != name], 0)
     for name in names}

from pprint import pprint
pprint(d)

Output

{'Frank': {'Jack': 0, 'Kevin': 0, 'Sam': 0},
 'Jack': {'Frank': 0, 'Kevin': 0, 'Sam': 0},
 'Kevin': {'Frank': 0, 'Jack': 0, 'Sam': 0},
 'Sam': {'Frank': 0, 'Jack': 0, 'Kevin': 0}}

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