user1741339
user1741339

Reputation: 515

mapping dictionary and lists python

What the easiest way if you have three lists

list [1,2,3] [a,b,c] [5,6,7]

to map it with a dictionary

{1:{'a':5}, 2:{'b':6}, 3:{'c':7}} 

Got a feeling you have to use zip ..

How would this be done in python where dictionary comprehension isn't possible

Upvotes: 1

Views: 119

Answers (4)

Shankar
Shankar

Reputation: 3624

Using izip which is better in terms of efficiency

from itertools import izip

a = [1, 2, 3]
b = ['a', 'b', 'c']
c = [5, 6, 7]

print {a: {b: c} for a, b, c in izip(a, b, c)}

Output:

{1: {'a': 5}, 2: {'b': 6}, 3: {'c': 7}}

Upvotes: 0

HYRY
HYRY

Reputation: 97271

Are the values in first & second list can be duplicated, for example:

a, b, c = [3,1,2,3,1], ['a','a','b','c','d'], [1,5,6,7,8]

If you need the order:

from collections import OrderedDict
od = OrderedDict()
for x, y, z in zip(a, b, c):
    if x not in od:
        od[x] = OrderedDict()
    od[x][y] = z
print od

output:

OrderedDict([(3, OrderedDict([('a', 1), ('c', 7)])), (1, OrderedDict([('a', 5), ('d', 8)])), (2, OrderedDict([('b', 6)]))])

if you don't need order:

from collections import defaultdict
dd = defaultdict(dict)
for x, y, z in zip(a,b,c):
    dd[x][y] = z
print dd

output:

defaultdict(<type 'dict'>, {1: {'a': 5, 'd': 8}, 2: {'b': 6}, 3: {'a': 1, 'c': 7}})

Upvotes: 0

mgilson
mgilson

Reputation: 309861

The 3-list case in your update is an easy one with zip:

d = {k:{k1:v1} for k,k1,v1 in zip(list1,list2,list3)}

Upvotes: 6

Andrew Clark
Andrew Clark

Reputation: 208435

Dictionaries don't have an order, so I am assuming you want to map them based on the order of the sorted keys. You can do that with the following:

>>> lst = [1, 2, 3]
>>> dct = {'a': 5, 'b': 6, 'c': 7}
>>> {i: {k: dct[k]} for i, k in zip(lst, sorted(dct))}
{1: {'a': 5}, 2: {'b': 6}, 3: {'c': 7}}

If you decide to use something like list of tuples instead of a dictionary to maintain the order, you could do the following:

>>> lst = [1, 2, 3]
>>> tups = [('a', 5), ('b', 6), ('c', 7)]
>>> {i: {k: v} for i, (k, v) in zip(lst, tups)}
{1: {'a': 5}, 2: {'b': 6}, 3: {'c': 7}}

Upvotes: 4

Related Questions