edmpg
edmpg

Reputation: 3

Append value to a list which in nested dictionary

Basically I need to populate d3 from d2 and d1

d1 = {'Spain':['Madrid,'Barcelona'],'France':['Paris','Nice'],'Germany':['Dortmund','Berlin']}
d2 = {'Madrid':[1,2]'Barcelona':[2],'Paris':[3,4],'Nice':[4],'Dortmund':[5],'Berlin':[6]}

Desired output d3 is as follows:

d3 = {'Spain':{'Madrid':[1,2]},{'Barcelona':[2]},'France':{'Paris':[3,4]},{'Nice':[4]},'Germany':{'Dortmund':{[5]},{'Berlin':[6]}}

I tried following but no luck, I am stuck

l = []
def getKeysByValue(dictOfElements, valueToFind):
    listOfKeys = list()
    listOfItems = dictOfElements.items()
    for item  in listOfItems:
    if item[1] == valueToFind:
        listOfKeys.append(item[0])
    return listOfKeys

for i in d2.keys():
    for j in d1.values():
        if i in j:
            name = str(getKeysByValue(d1,j))
            l.append({i:name2})
            d3[name] = l
print(d3)

Upvotes: 0

Views: 68

Answers (3)

alec
alec

Reputation: 6112

You can use a dict comprehension to achieve this.

d1 = {'Spain': ['Madrid','Barcelona'],
      'France': ['Paris','Nice'],
      'Germany': ['Dortmund','Berlin']}

d2 = {'Madrid': [1,2],
      'Barcelona': [2],
      'Paris': [3,4],
      'Nice': [4],
      'Dortmund': [5],
      'Berlin':[6]}

d3 = {k: {city: d2[city] for city in v} for k, v in d1.items()}

It is iterating through the keys and values of d1. For every key, the value is a dictionary with each element in the value list as the key, and the d2 value of that key as the value.

Upvotes: 1

quamrana
quamrana

Reputation: 39354

You can simply create d3 like this:

d1 = {'Spain':['Madrid','Barcelona'],'France':['Paris','Nice'],'Germany':['Dortmund','Berlin']}

d2 = {'Madrid':[1,2],'Barcelona':[2],'Paris':[3,4],'Nice':[4],'Dortmund':[5],'Berlin':[6]}


d3 = {country:{city:d2[city] for city in cities} for (country,cities) in d1.items()}

print(d3)

Output:

{'Spain': {'Madrid': [1, 2], 'Barcelona': [2]}, 'France': {'Paris': [3, 4], 'Nice': [4]}, 'Germany': {'Dortmund': [5], 'Berlin': [6]}}

I have taken the liberty of correcting your data sources.

Upvotes: 1

AzBakuFarid
AzBakuFarid

Reputation: 1

d1 = {'Spain':['Madrid','Barcelona'],'France':['Paris','Nice'],'Germany':['Dortmund','Berlin']}

d2 = {'Madrid':[1,2], 'Barcelona':[2],'Paris':[3,4],'Nice':[4],'Dortmund':[5],'Berlin':[6]} d3 = {}

for k, v in d1.items():

data = {}

    for item in v:

        if item in d2:    #  to escape from an KeyError from d2 dictionary

            data[item] = d2[item]

 d3[k] = data

Upvotes: -1

Related Questions