1
votes

How can I create a big dictionary in Python taking key value pairs from multiple pair of lists. For example, we have 6 lists, namely key1,val1,key2,val2 and key3,val3. Now I want to create a dictionary containing all keys from key1, key2 and key3 and corresponding values from val1, val2, val3 respectively. for example:

val1 = ['3/12/2017', '12/18/2017', '12/18/2017', '12/12/2017']
key1 = [32, 45, 107, 150]
val2 = ['2000-03-13', '2014-11-31']
key2 = [166, 244]

I want the dictionary as given below:

big_dict = {32: '3/12/2017', 107: '12/18/2017', 45: '12/18/2017', 150: '12/12/2017', 244: '2014-11-31', 166: '2000-03-13'}

How can this be done? Thanks

6
On what basis, would the key items would be assigned to the value items? It doesn't seem to be ordered.Arkistarvh Kltzuonstev

6 Answers

3
votes

Using zip and simple concatenation:

big_dict = dict(zip(key1+key2, val1+val2))

If you have an unknown number of key and value lists, use itertools.chain and zip:

from itertools import chain

big_dict = dict(zip(chain(*key_lists), chain(*val_lists)))
2
votes

A simple answer would be this, Although there are much efficient ways to do this.

val1 = ['3/12/2017', '12/18/2017', '12/18/2017', '12/12/2017']
key1 = [32, 45, 107, 150]
val2 = ['2000-03-13', '2014-11-31']
key2 = [166, 244]

big_dict = {}

big_dict.update(dict(zip(key1, val1)))
big_dict.update(dict(zip(key2, val2)))

Or combine lists before and do a one-liner

keys = key1 + key2 # Make sure they are unique however or else dict() will show incorrect results
values = val1 + val2

big_dict.update(dict(zip(keys, values)))

print(big_dict)
1
votes

try this code:

a=(dict(zip(key1,val1)))
b=(dict(zip(key2,val2)))
d = a.copy()
d.update(b)
0
votes

add all the lists to a common list and automate the process, as such:

combined_dict = {}

values_lists = [ val1, val2 ]
keys_lists = [ key1, key2 ]

for itr in range(len(keys_list)):
    for list_itr in range(len(keys_list[itr])):
        combined_dict[keys_list[itr][list_itr]] = values_lists[itr][list_itr]
0
votes

I would concat the lists, and by using zip merge it into keys and values (dictionary).

val1 = ['3/12/2017', '12/18/2017', '12/18/2017', '12/12/2017']
key1 = [32, 45, 107, 150]
val2 = ['2000-03-13', '2014-11-31']
key2 = [166, 244]

keys = key1 + key2
vals = val1 + val2
d = dict(zip(keys, vals))

print (d)
# {32: '3/12/2017', 45: '12/18/2017', 107: '12/18/2017', 150: '12/12/2017', 166: '2000-03-13', 244: '2014-11-31'}
0
votes

You can extend the list and the zip them and create a dictionary like below

val1 = ['3/12/2017', '12/18/2017', '12/18/2017', '12/12/2017']
key1 = [32, 45, 107, 150]
val2 = ['2000-03-13', '2014-11-31']
key2 = [166, 244]

key1.extend(key2)
val1.extend(val2)

newdict = {k: v for k, v in zip(key1, val1)}

print(newdict)