用Python中的特定条件匹配嵌套字典中列表类型的值

2024-06-26 13:34:09 发布

您现在位置:Python中文网/ 问答频道 /正文

如果这是一个愚蠢的问题,我很抱歉,因为我是python和编码新手。 一定要问在理解我的问题时是否有任何疑问

我有一本嵌套字典

Nested_Dictionary = {0:{'item':['Cat','Dog'],'set':'a'},1:{'item':['Living','Dog'],'set':'b'},2:{'item':['Mouse','Cat'],'set':'c'},3:{'item':['Cat','Dog'],'set':'d'},4:{'item':['Cat','Living'],'set':'e'},5:{'item':['Mouse','Cat'],'set':'f'},6:{'item':['Living','Cat'],'set':'g'},7:{'item':['Pigeon','Living'],'set':'h'},8:{'item':['Cat','Dog'],'set':'i'},9:{'item':['Living','Dog'],'set':'j'},10:{'item':['Mouse','Cat'],'set':'k'},11:{'item':['Living','Living'],'set':'l'}}

我想匹配嵌套的'item'键中的列表值,并获取它们的上键,然后创建一个新字典,其中'item'列表值作为键,所有匹配元素的列表作为值。问题是,如果“生活”在列表“项目”中的任何位置,则另一个位置仅用于查找匹配项;如果两个位置都是“Living”,则所有匹配项都会附加该键。 输出应为:

{'Cat,Dog':[0,3,8,1,9,4,11], 'Mouse,Cat':[2,5,10,6,11], 'Pigeon,Living':[7,11]}

“鸽子,活着”是独一无二的,因为鸽子只有一次“活着,活着”附在所有的后面

到目前为止,我已经能够匹配项目一次,而不必考虑“生活”在单一的立场;并通过以下方式在“项”中添加键“Living,Living”:

compari = defaultdict(list)
for k,v in Nested_Dictionary.items():
    for k1,v1 in v.items():
        if x == 'item':
            compari[v1[0]+','+v1[1]].append(k)   #To match items and append their upper keys
compari = {key:value for key,value in compari.items()}
p=compari.get('Living,Living')                   #To get list of keys in 'Living,Living'
del compari['Living,Living']                     #Deleting the 'Living,Living' key 
for x,y in compari.items():
    compari[x].append(p)              #appending list of keys in 'Living,Living' to all elements
print(compari)

我得到的输出是:

{'Cat,Dog': [0,3,8,11], 'Living,Dog': [1,9,11], 'Mouse,Cat': [2,5,10,11], 'Cat,Living': [4,11], 'Living,Cat': [6,11], 'Pigeon,Living': [7,11]}

我一直在比较和查找匹配项,其中项目列表中只有一个位置是“活的”,我必须根据另一个位置查找匹配项。还建议是否有更好的方法来做我已经做过的事情。谢谢


Tags: 项目in列表foritemsitemlistcat
1条回答
网友
1楼 · 发布于 2024-06-26 13:34:09

您可以使用collections.defaultdict存储正在运行的匹配和原始字典键。这个答案根据item内容将输入分成特定的组:完整的item值保存在full中,任何至少有一个Livingitem都进入p

from collections import defaultdict
Nested_Dictionary = {0:{'item':['Cat','Dog'],'set':'a'},1:{'item':['Living','Dog'],'set':'b'},2:{'item':['Mouse','Cat'],'set':'c'},3:{'item':['Cat','Dog'],'set':'d'},4:{'item':['Cat','Living'],'set':'e'},5:{'item':['Mouse','Cat'],'set':'f'},6:{'item':['Living','Cat'],'set':'g'},7:{'item':['Pigeon','Living'],'set':'h'},8:{'item':['Cat','Dog'],'set':'i'},9:{'item':['Living','Dog'],'set':'j'},10:{'item':['Mouse','Cat'],'set':'k'},11:{'item':['Living','Living'],'set':'l'}}
d, full, p = defaultdict(list), set(), {'partial':set(), 'full':set()}
#separate complete `item`s from those that have "Living"
for a, b in Nested_Dictionary.items():
   if 'Living' in b['item']:
      p['full' if sum(i == 'Living' for i in b['item']) == 2 else 'partial'].add((a, tuple(b['item'])))
   else:
      d[(x:=tuple(b['item']))].append(a)
      full.add(x)

#match `item`s that have any partial occurrences of "Living"
for v, i in p['partial']:
   if (m:=[b for b in full if any(j == k for j, k in zip(i, b))]):
      for x in m:
         d[x].append(v)
   else:
      d[i].append(v)
      full.add(i)

#update `d` with key value of any `item`s that just have "Living"
for v, i in p['full']:
   for x in full:
      d[x].append(v)

print({','.join(a):b for a, b in d.items()})

输出:

{'Cat,Dog': [0, 3, 8, 1, 4, 9, 11], 'Mouse,Cat': [2, 5, 10, 6, 11], 'Pigeon,Living': [7, 11]}

相关问题 更多 >