Python programmer
Python programmer

Reputation: 75

Replacing the keys of a dictionary with values of another dictionary to create a new dictionary

I am trying to replace the keys in the ages dictionary with the values (the names) of the d1 dictionary (as per below).

I want the final dictionary to look something like: [Callum: 20, Herrara, 21 etc] instead of just have the last value [Liz: 19] which I am currently getting.

Here is my code

d1 = {
0 : "Callum",
1: "Herrera",
2: "Bob",
3: "Bill",
4: "Liz",}

ages= {
0: 20,
1: 21,
2: 40,
3: 20,
4: 19,}

for v in d1.values():
    A=v

for v in ages.values():
    B= v

dictionary3= {
    A:B,
}

print (dictionary3)

Upvotes: 2

Views: 67

Answers (2)

Julian Camilleri
Julian Camilleri

Reputation: 3095

You can simply iterate over the names and do the following:

names = {
    0: "Callum",
    1: "Herrera",
    2: "Bob",
    3: "Bill",
    4: "Liz"
}

ages = {
    0: 20,
    1: 21,
    2: 40,
    3: 20,
    4: 19
}

name_age = {}
for key, value in names.items():
    name_age[value] = ages.get(key, -1)

>>> print(name_age)
{'Callum': 20, 'Bill': 20, 'Bob': 40, 'Liz': 19, 'Herrera': 21}

Although seems quite odd that you're using a dict as a list; if you'd like to mimic this behaviour using a list you can do so using enumerate() which will produce indexes accordingly.

The ideal scenario is to use a proper data structure as shown below; but it solely depends on your requirements.

name_age = [
    {
        "name": "Callum",
        "age": 20
    },
    {
        "name": "Herrera",
        "age": 21
    }
]

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

Your attempts rewrite the data at each iteration. Plus they lose the relation between the name and the index by only iterating on the values. Time to rethink the approach from scratch.

I would combine both dict data and build a new dictionary using dictionary comprehension:

result = {name:ages[index] for index,name in d1.items()}

>>> result
{'Bill': 20, 'Bob': 40, 'Callum': 20, 'Herrera': 21, 'Liz': 19}

note that d1 is used just like a list of tuples. Only ages is used like a real dictionary. You can insert default ages to avoid key errors like this:

result = {name:ages.get(index,"unknown") for index,name in d1.items()}

so persons with missing index get a "unknown" age.

Upvotes: 2

Related Questions