简体   繁体   中英

how join list tuple and dict into a dict?

how join list tuple and dict into a dict?

['f','b','c','d'] (1,2,3) and {'a':'10'}
d excluded for list be compatible with the tuple

output {'f':'1','b':'2','c':'3','a':'10'}

You can make a dict from keys and values like so:

keys = ['a','b','c','d']
values = (1,2,3)
result = dict(zip(keys, values)) # {'a': 1, 'c': 3, 'b': 2}

Then you can update it with another dict

result.update({ 'f' : 5 })
print result # {'a': 1, 'c': 3, 'b': 2, 'f': 5}
dict(zip(a_list, a_tuple)).update(a_dictionary)

when a_list is your list, a_tuple is your tuple and a_dictionary is your dictionary.

EDIT: If you really wanted to turn the numbers in you tuple into strings than first do:

new_tuple = tuple((str(i) for i in a_tuple))

and pass new_tuple to the zip function.

This will accomplish the first part of your question:

dict(zip(['a','b','c','d'], (1,2,3)))

However, the second part of your question would require a second definition of 'a', which the dictionary type does not allow. However, you can always set additional keys manually:

>>> d = {}
>>> d['e'] = 10
>>> d
{'e':10}

The keys in a dictionary must be unique, so this part: {'a':'1','a':'10'} is impossible.

Here is code for the rest:

l = ['a','b','c','d']
t = (1,2,3)

d = {}
for key, value in zip(l, t):
    d[key] = value

Something like this?

>>> dict({'a':'10'}.items() + (zip(['f','b','c','d'],('1','2','3'))))
{'a': '10', 'c': '3', 'b': '2', 'f': '1'}

Since noone has given an answer that converts the tuple items to str yet

>>> L=['f','b','c','d']
>>> T=(1,2,3)
>>> D={'a':'10'}
>>> dict(zip(L,map(str,T)),**D)
{'a': '10', 'c': '3', 'b': '2', 'f': '1'}

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