【问题标题】:Create new list of dictionary from two list of dictionaries从两个字典列表创建新的字典列表
【发布时间】:2020-10-18 20:23:33
【问题描述】:

我有两个字典列表,想从现有的两个字典列表中创建新的字典列表。 dict1 有关于人的所有详细信息(pid、pname、pscore、sid)和 dict2 有关于城市的人的详细信息(pid、cid、cscore)想要创建新的字典列表,其中 dict1 的 pid 匹配 dict2 的 pid 并添加 pid, pname、pscore、cscore 来自两个字典列表,其中匹配发生在 new_dict 列表中。任何帮助将不胜感激。提前致谢。

   dict1 = [{'pid': [7830351800, 8756822045, 7985031822, 8882181833],
  'pname': ['ABC', 'XYZ', 'QWE', 'MNQ'],
  'pscore': [0.8, 0.8, 0.8, 0.8],
  'sid': 8690694}]
 dict2 = [{'pid': 7830351800, 'cid': [1, 2, 3, 4], 'cscore': [0.8, 0.78, 0.7, 0.45]},
 {'pid': 8756822045, 'cid': [5, 6, 7, 8], 'cscore': [0.9, 0.88, 0.8, 0.75]},
 {'pid': 7985031822, 'cid': [9, 10, 11, 12], 'cscore': [0.5, 0.48, 0.3, 0.25]},
 {'pid': 8882181833, 'cid': [2, 13, 14, 15], 'cscore': [0.6, 0.58, 0.5, 0.45]}]
   new_dict = [{'pid': 7830351800,
  'pname': 'ABC',
  'pscore': 0.8,
  'cid': [1, 2, 3, 4],
  'cscore': [0.8, 0.78, 0.7, 0.45]},
 {'pid': 8756822045,
  'pname': 'XYZ',
  'pscore': 0.8,
  'cid': [5, 6, 7, 8],
  'cscore': [0.9, 0.88, 0.8, 0.75]},
 {'pid': 7985031822,
  'pname': 'QWE',
  'pscore': 0.8,
  'cid': [9, 10, 11, 12],
  'cscore': [0.5, 0.48, 0.3, 0.25]},
 {'pid': 8882181833,
  'pname': 'MNQ',
  'pscore': 0.8,
  'cid': [2, 13, 14, 15],
  'cscore': [0.6, 0.58, 0.5, 0.45]}]

我尝试了下面的代码,但遇到了错误。我无法理解如何解决这个问题。刚开始学python:

new_dict = {}
for k, v in dict1[0].items():
    if v[0] in dict2[0]['pid']:
        new_dict = dict({'pid': v[0], 'pname' :v[0], 'pscore':v[0], 'cid':dict2[0]['cid'], 'cscore':dict2[0]['score']})
        print(new_dict)

【问题讨论】:

  • 这是 2 个列表...
  • @Ironkey 是的,我的字典不好,让我更新我的问题。谢谢
  • 另外,你能告诉我们你已经尝试过什么吗?我们真的不为这里的人编写代码。
  • 请从intro tour 重复on topichow to ask。 “告诉我如何解决这个编码问题?”与 Stack Overflow 无关。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。 Stack Overflow 无意取代现有的教程和文档。
  • Edit 在您的问题中添加更多详细信息,请勿添加评论

标签: python python-3.x list dictionary


【解决方案1】:
dict1 = dict1[0]

pname_dict = {key:value for key,value in zip(dict1['pid'], dict1['pname'])}
pscore_dict = {key:value for key,value in zip(dict1['pid'], dict1['pscore'])}
ans = dict2.copy()

for d in ans:
    d['pname'] = pname_dict[d['pid']]
    d['pscore'] = pscore_dict[d['pid']]

输出:

>> ans

[{'pid': 7830351800,
  'cid': [1, 2, 3, 4],
  'cscore': [0.8, 0.78, 0.7, 0.45],
  'pname': 'ABC',
  'pscore': 0.8},
 {'pid': 8756822045,
  'cid': [5, 6, 7, 8],
  'cscore': [0.9, 0.88, 0.8, 0.75],
  'pname': 'XYZ',
  'pscore': 0.8},
 {'pid': 7985031822,
  'cid': [9, 10, 11, 12],
  'cscore': [0.5, 0.48, 0.3, 0.25],
  'pname': 'QWE',
  'pscore': 0.8},
 {'pid': 8882181833,
  'cid': [2, 13, 14, 15],
  'cscore': [0.6, 0.58, 0.5, 0.45],
  'pname': 'MNQ',
  'pscore': 0.8}]

创建 2 个字典以匹配 pid ->pnamepid->pscore。这些字典用于将其他 2 个键值添加到 dict2

【讨论】:

  • 谢谢它的帮助,简单而干净的解决方案。
猜你喜欢
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2022-08-03
  • 2022-01-16
  • 1970-01-01
  • 2021-07-28
  • 2018-11-06
  • 2018-12-17
相关资源
最近更新 更多