【问题标题】:Create a new dictionary from 2 existing dictionory (1 nested dictionory , 1 dictionory of lists) python从 2 个现有字典(1 个嵌套字典,1 个列表字典)python 创建一个新字典
【发布时间】:2021-02-06 22:50:58
【问题描述】:

我有两个字典 K 和 L。K 是列表字典L 是嵌套字典

 K={
    'k1':[1,3,2],
    'k2':[3,4,5],
    'k3':[9,10,11]
    }

L = {
'l1':{'a':'1','b':'1','c':'2'},
'l2':{'a':'1','b':'3','c':'2'},
'l3':{'a':'1','b':'2','c':'2'},
'l4':{'a':'1','b':'4','c':'2'}
}

我需要什么: 我想根据以下条件创建一个新的列表字典

  1. 我需要检查列表的 K 字典中是否存在 b 的 L 值
  2. 如果存在,我需要返回带有 K 键的新字典 字典和 L 字典的键。

对于上面的例子,我需要返回这样的东西

M = {'k1':[l1,l3,l2]
     'k2':[l2,l4]
     }

这是我尝试过的代码:

M= {}
for k, v in K.items():
  temp = []
  for i in v:
    if L[i]['b'] in K[k]:
      temp.append(i)
      M[k] = temp
    
print(M)

【问题讨论】:

  • 什么是k1k2k3,什么是l1l2l3
  • 这些是字典的关键
  • 所以你应该返回[1,2,3] as [l1,l2,l3] ?
  • @Suman 不。我们需要将这些值与 b 值进行比较。然后将 L 对应的键作为新字典中的值返回。
  • @Fusdev,看看我的答案...更简单...试试看...

标签: python python-3.x


【解决方案1】:

这是您的解决方案:

new_dict, M = dict(), dict()

for key, val in L.items():
    new_dict[val['b']] = key

for key, val in K.items():
    for x in val:

        if str(x) in new_dict:
            tmp = new_dict[str(x)]
            lst = M[key] if key in M else list()
            lst.append(tmp)
            M[key] = lst
print(M)

对于以下 K、L:

K = {
'k1':[1,3,2],
'k2':[3,4,5],
'k3':[9,10,11]
}

L = {
'l1':{'a':'1','b':'1','c':'2'},
'l2':{'a':'1','b':'3','c':'2'},
'l3':{'a':'1','b':'2','c':'2'},
'l4':{'a':'1','b':'4','c':'2'}
}

输出 M:

M = {
'k2': ['l2', 'l4'], 
'k1': ['l1', 'l2', 'l3']
}

[ 考虑的 b 值的 L 具有 唯一 值,如果不是,则必须将其作为列表存储在 new_dict 字典中。]

【讨论】:

  • 非常感谢您的回答。L = { 'l1':{'a':'1','b':'1','e':'2'}, 'l2':{'a':'1','b':'3','f':'2'}, 'l3':{'a':'1','b':'2','g':'2'}, 'l4':{'a':'1','b':'4','h':'2'} }
  • 有没有办法通过将它们添加到列表中来检查不同的值,例如 e,f,g,h new_dict[val['b']] = key
  • 是的,您可以将它们添加到 new_dict 但在这种情况下,lst 可能有重复值,因此如果您想要唯一值,只需将 list 替换为 set .
  • list_g = ['e','f','g','h'] for u in list_g: for key, val in L.items(): new_dict[val[u]] = key 这段代码有什么问题?
【解决方案2】:

您在L 此处L[I] 中查找错误内容。我会通过最初从L 创建一个查找来做到这一点,这样您就不必为K 中的每个键循环遍历L。从那里您可以通过K 一次,从查找中查找项目。

使用defaultdict 还允许您处理L 具有相同b 值的情况

from collections import defaultdict

b_val_to_l = defaultdict(set)
for lkey, ldict in L.items():
    # For each ldict, extract the 'b' value, convert to an int and add the
    # l key to the set of l values for the corresponding b value
    b_val_to_l[int(ldict['b'])].add(lkey)

print(b_val_to_l)

M = defaultdict(list)
for k, v in K.items():
  for i in v:
      # For each value in the k, get the set of corresponding l values
      b_set = b_val_to_l.get(i, set())

      # Add to the output dict
      M[k].extend(list(b_set))

print(M)

【讨论】:

  • 只是打印出来,这样你就可以看到发生了什么。你可以拿出来
  • M 也是defaultdict,如果需要,可以调用dict(M) 使其成为普通的dict
  • list_g = ['e','f','g','h'] for u in list_g: for lkey, ldict in L.items(): # For each ldict, extract the 'b' value, convert to an int and add the # l key to the set of l values for the corresponding b value b_val_to_l[int(ldict[u])].add(lkey) 这段代码有什么问题
  • ldict 没有正确的密钥,例如'e'
  • 查找realpython.com/python-keyerror。不过我也帮不了你了,祝你好运!
【解决方案3】:

这样做:

Mtemp = { k: [l for l in L
            if int(L[l]['b']) in K[k]
        ] for k in K }

# Mtemp can have None values, so let's remove them...
M = { k: l for k, l in Mtemp.items() if len(l) > 0 }

输出:

{'k1': ['l1', 'l2', 'l3'], 'k2': ['l2', 'l4']}

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2020-12-30
    相关资源
    最近更新 更多