Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how join list tuple and dict into a dict?

Tags:

python

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'}
like image 388
user422100 Avatar asked Aug 16 '10 20:08

user422100


People also ask

How do you obtain a list of tuples of key-value pairs in a dictionary dict?

One of the built-in methods for dictionaries is the . items() methods, which returns a tuple of tuples of the key value pairs found inside the dictionary. We can use this method and pass it into the list() function, in order to generate a list of tuples that contain the key value pairs from our dictionary.

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

Can we use list or tuple as key in dictionary?

A tuple containing a list cannot be used as a key in a dictionary. Answer: True. A list is mutable. Therefore, a tuple containing a list cannot be used as a key in a dictionary.


3 Answers

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}
like image 112
Jochen Ritzel Avatar answered Oct 06 '22 12:10

Jochen Ritzel


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.

like image 29
snakile Avatar answered Oct 06 '22 12:10

snakile


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}
like image 45
pmalmsten Avatar answered Oct 06 '22 12:10

pmalmsten