1

My dictionary :

d={'a':'a1,a2,a3,a4','b':'b1,b2,b3,b4',c:'c1,c2,c3,c4'}

and so on d,e,f,....

d2={'a1':'a11,a12,a13,a14,a15','a2':'a21,a22,a23,a24,a25'} 

and so on for a3,a4,a5,b1,b2....

Expected output

dict1={'a':{'a1':'a11,a12,a13,a14,a15','a2':'a21,a22,a23,a24,a25'}} 

and so on for rest

My Output

dict1={'a':{'a1':'a11,a12,a13,a14,a15'},'a2':'a21,a22,a23,a24,a25'}

and so on then again

 'b':{'b1':'b11,b12,b13,b14,b15'},'b2':'b21,b22,b23,b24,b25'}

My Code:

dict1={}
for i in d:
    q=d[i].split(",")
    for j in q:
        dict1[i] = {}
        if j in d2:
            dict1[i][j] = d2[j]
            dict1.update(dict1[i])

Any help would be very useful

2 Answers 2

1

You can try nested dictionary comprehension with list comprehension

d={'a':'a1,a2,a3,a4','b':'b1,b2,b3,b4','c':'c1,c2,c3,c4'}
d2={'a1':'a11,a12,a13,a14,a15','a2':'a21,a22,a23,a24,a25', 'b1':'b11,b12,b13,b14,b15','b2':'b21,b22,b23,b24,b25'}
dict1 = {k: {i: d2[i] for i in v.split(",") if i in d2} for k, v in d.items()})
print(dict1)

Output in this case

{'a': {'a1': 'a11,a12,a13,a14,a15', 'a2': 'a21,a22,a23,a24,a25'}, 'b': {'b1': 'b11,b12,b13,b14,b15', 'b2': 'b21,b22,b23,b24,b25'}, 'c': {}}

So if there will be values in d2 about the the c's they will be in the dict1 results as well.

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe you can try with:

dict1={}
for i in d:
    q=d[i].split(",")
    for j in q:
        if not dict1.get(i, None):
            dict1[i] = {}
        if j in d2:
            dict1[i][j] = d2[j]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.