Py学习  »  Python

Python:比较字典中键之间的值重叠

Liquidity • 6 年前 • 2095 次点击  

我有一个 dict 这样地:

dict = defaultdict(list, {'a': [['1', '2', 'A', 'cat'],
                               ['1', '3', 'A', 'dog']], 
                          'b': [['1', '2', 'A', 'cat'],
                               ['1', '3', 'A', 'dog']],
                          'c': [['1', '2', 'A', 'cat'],
                               ['2', '2', 'A', 'snake'],
                               ['2', '2', 'A', 'bird']]}

我想使用 对于每个值。(值列表中的每个位置都必须匹配,才能将其视为键之间的匹配)

自从 a b 分享 ['1', '3', 'A', 'dog'] c 不, a/b: ['1', '3', 'A', 'dog'] .

, c类 ,全部共享 ['1', '2', 'A', 'cat'] a/b/c: ['1', '2', 'A', 'cat'] .

只有 c类 ['2', '2', 'A', 'snake'] c: ['2', '2', 'A', 'snake']

首选的输出是一个结合上述内容的字典,类似于

combine_dict = {'a/b': ['1', '3', 'A', 'dog'], 'a/b/c': ['1', '2', 'A', 'cat'], 'c': [['2', '2', 'A', 'snake'], ['2', '2', 'A', 'bird']]}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53735
文章 [ 1 ]  |  最新文章 6 年前
Ajax1234
Reply   •   1 楼
Ajax1234    7 年前

你可以用 collections.defaultdict :

import collections
d = {'a': [['1', '2', 'A', 'cat'], ['1', '3', 'A', 'dog']], 'b': [['1', '2', 'A', 'cat'], ['1', '3', 'A', 'dog']], 'c': [['1', '2', 'A', 'cat'], ['2', '2', 'A', 'snake'], ['2', '2', 'A', 'bird']]}
new_d = collections.defaultdict(list)
for a, b in d.items():
  for i in b:
     new_d[tuple(i)].append(a)


new_r = collections.defaultdict(list)
for a, b in new_d.items():
   new_r['/'.join(b)].append(list(a))

new_result = {a:b[0] if len(b) == 1 else b for a, b in new_r.items()}

{'a/b/c': ['1', '2', 'A', 'cat'], 'a/b': ['1', '3', 'A', 'dog'], 'c': [['2', '2', 'A', 'snake'], ['2', '2', 'A', 'bird']]}