简体   繁体   中英

Adding multiple keys to the dictionary (python)

I create dictionary in python: d = dict.fromkeys(['one', 'two', 'three'], 1)

But I don't know, how can I add the multiple keys to this dictionary like ['one2', 'two2', 'three2'] -> 2

So, result dictionary should be:

['one', 'two', 'three'] -> 1 ['one2', 'two2', 'three2'] -> 2

one way is updating with the result of another dict.fromkeys dictionary:

d = dict.fromkeys(['one', 'two', 'three'], 1)
d.update(dict.fromkeys( ['one2', 'two2', 'three2'] , 2))

result:

{'one': 1, 'two': 1, 'two2': 2, 'three2': 2, 'three': 1, 'one2': 2}

Can be tedious if you have more data to update like this. In that case, make a list of tuples with keys/value and "flatten" it using dict comprehension:

kv = [(['one', 'two', 'three'], 1),(['one2', 'two2', 'three2'] , 2)]

d = {k:v for kl,v in kv for k in kl}

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