dyao
dyao

Reputation: 1011

Creating a nested dictionary

Let say I have a list and a dictionary respectively:

a=['a.pdf','b.pdf']

b = {'a':['email1', 'email2'], 'b':['email3']}

And I want the end result to look like this nested dictionary using a loop.

x={'a.pdf':{'a':['email1', 'email2']}, 'b.pdf':{'b':['email3']}}

I tried using a for loop like this:

for element in a:
    x={}
    for key, value in b.items()
       x[element]={}
       x[found][key]=value

 print(x)

This doesn't work because dict x is getting reassigned new values through each iteration so the end result is:

 {'b.pdf':{'b':['email3']}}

So I assume a dict comprehension is the way to go? I'm having a tough time figuring out how to write this into a dictionary comprehension.

Upvotes: 1

Views: 140

Answers (4)

henry
henry

Reputation: 593

a = ['a.pdf','b.pdf','c.pdf']
b = {'a':['email1', 'email2'], 'b':['email3']}
def match(m):
    return m[0]
d = { e: {match(e): b[match(e)]} for e in a if match(e) in b }

You can change the match func to your requirement.

Upvotes: 1

Martin
Martin

Reputation: 1069

x = {top_key: {sub_key: b[sub_key] for sub_key in b if sub_key == top_key[0]} for top_key in a}

Assuming the key format you were using in your example.

Upvotes: 1

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52223

>>> a = ['a.pdf','b.pdf']
>>> b = {'a':['email1', 'email2'], 'b':['email3']}
>>> c = {x: dict((y,)) for x, y in zip(a, b.items())}
>>> print c
{'a.pdf': {'a': ['email1', 'email2']}, 'b.pdf': {'b': ['email3']}}

Upvotes: 1

mmachine
mmachine

Reputation: 926

You may use:

a=['a.pdf','b.pdf']
b = {'a':['email1', 'email2'], 'b':['email3']}
new_dict = {k:v for k,v in zip(a,b.items())}

Result:

print(new_dict)
{'a.pdf': ('a', ['email1', 'email2']), 'b.pdf': ('b', ['email3'])}

Upvotes: 1

Related Questions