简体   繁体   English

用另一个字典的值替换一个字典的键以创建一个新的字典

[英]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). 我试图用d1词典的值(名称)替换ages词典中的键(如下所示)。

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. 我希望最终的字典看起来像: [Callum: 20, Herrara, 21 etc]而不是只有我目前正在获取的最后一个值[Liz: 19]

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)

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: 我将结合dict数据并使用字典理解来构建新字典:

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 . 请注意, d1的使用就像tuples列表一样。 Only ages is used like a real dictionary. 只有ages的使用才像真正的字典一样。 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. 因此缺少索引的人的年龄是"unknown"

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 ; 尽管您使用dict作为list似乎很奇怪; if you'd like to mimic this behaviour using a list you can do so using enumerate() which will produce indexes accordingly. 如果您想使用list来模仿此行为,则可以使用enumerate() ,该方法将相应地产生索引。

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
    }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM