【问题标题】:split a dictionary among keys coming from 2 different other dictionaries在来自 2 个不同的其他字典的键之间拆分字典
【发布时间】:2017-04-13 04:25:53
【问题描述】:

我有 3 部字典:

dict1 = {'Name1':'Andrew','Name2':'Kevin'....'NameN':'NameN'}- this would have maximum 20 names
dict2 = {'Travel':'Andrew','Footbal':'Kevin',...'Nhobby':'NameN'}- this would have as many names as there are in dict1
dict3 = {'Travel':'ID01','Footbal':'ID02','Travel':'ID03','Photo':'ID04','Footbal':'ID05','Photo':'ID06','Climbing':'ID07'....}

我想合并这 3 个字典,以便第 3 个以这种方式结束:

 dict3 = {'Andrew':'ID01','Kevin':'ID02','Andrew':'ID03','Kevin':'ID04','Kevin':'ID05','Kevin':'ID06','Andrew':'ID07',....}. Basically the hobbies that are in the dict 2 will be kept while the remaining hobbies will be split among the total number of names with a +1 in the case of an uneven number of hobbies.

我已经从这里Merge dictionaries retaining values for duplicate keys 尝试了合并功能,但我很难将 dict3 平均分配给所有名称。

【问题讨论】:

  • 您需要的输出是不可能的。字典必须有唯一的键。

标签: python pandas dictionary merge split


【解决方案1】:

只有当 dict2 的值是唯一的(因为它们将成为结果字典的键)时,您想要的输出才有可能。在这种情况下,您可以使用:

res_dict = {val: dict3[dict2.keys()[dict2.values().index(val)]] for val in dict1.values()}

输出:

>>> dict1 = {'Name1': 'Andrew', 'Name2': 'Kevin'}
>>> dict2 = {'Travel': 'Andrew', 'Footbal': 'Kevin'}
>>> dict3 = {'Travel': 'ID01', 'Footbal': 'ID02'}

>>> res_dict = {val: dict3[dict2.keys()[dict2.values().index(val)]] for val in dict1.values()}
>>> res_dict
{'Andrew': 'ID01', 'Kevin': 'ID02'}

如果您的 dict2 的值不是唯一的,您可以使用列表来存储 res_dict 值,如下所示:

dict1 = {'Name1': 'Andrew', 'Name2': 'Kevin'}
dict2 = {'Travel': 'Andrew', 'Footbal': 'Kevin', 'Photo': 'Andrew'}
dict3 = {'Travel': 'ID01', 'Footbal': 'ID02', 'Photo': 'ID03'}

res_dict = {}

for val in dict1.values():
    val_keys = []
    for key in dict2.keys():
        if dict2[key] == val:
            val_keys.append(key)
    for item in val_keys:
        if dict2[item] in res_dict:
            res_dict[dict2[item]].append(dict3[item])
        else:
            res_dict[dict2[item]] = [dict3[item]]

输出:

>>> res_dict
{'Andrew': ['ID03', 'ID01'], 'Kevin': ['ID02']}

【讨论】:

  • 嘿,ettanany,这似乎有效,但只有当你在 dict3 中有一次键时,我的 dict 有重复键
  • 看看我的答案的开头,我提到它只有在 dict2 的值是唯一的情况下才有效,因为字典不能包含具有相同键的多个项目。
  • @AndreiCozma - “我的字典有重复的键”不,它没有。
  • @AndreiCozma 请看看我编辑的答案,让我知道它对你有帮助/
猜你喜欢
  • 2021-11-15
  • 2018-01-19
  • 2014-05-27
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-20
相关资源
最近更新 更多