简体   繁体   English

Python-删除字典中的嵌套列表

[英]Python - Remove nested lists in dictionary

I have a dict named results . 我有一个名为results的字典。

the dict is structured in this format: 字典的结构如下:

{'a': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']], 'b': [['2', '2', '4'],['2', '2', '2'],['1', '2', '4']], 'c': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']]}

I wish to remove the duplicate nested lists for each key, therefore leaving the dict with: 我希望为每个键删除重复的嵌套列表,因此将字典保留为:

{'a': [['1', '2', '4'],['1', '2', '2']], 'b': [['2', '2', '4'],['2', '2', '2'],['1', '2', '4']], 'c': [['1', '2', '4'],['1', '2', '2']]}

I have tried: 我努力了:

newdict = {}
for k, v in results.items():
    for i in v:
        if i not in i:
            newdict[k] = i

any help? 有什么帮助吗? thanks in advance! 提前致谢!

Your code is wrong beyond repair (sorry), mostly because of those 2 lines: 您的代码是错误的,无法修复(抱歉),主要是因为以下两行:

 if i not in i:  # makes no sense testing if something is inside itself
      newdict[k] = i   # overwrites the key with one list

You'd have to count each list, and only keep one occurrence of each. 您必须计算每个列表,并且每个列表只保留一次。

If order doesn't matter you could do that with a nested dict/set/list comprehension. 如果顺序无关紧要,您可以使用嵌套的dict / set / list理解来完成。

results = {'a': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']], 'b': [['2', '2', '4'],['2', '2', '2'],['1', '2', '4']], 'c': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']]}

newdict = {k:[list(y) for y in {tuple(x) for x in v}] for k,v in results.items()}

print(newdict)

result: 结果:

{'a': [['1', '2', '2'], ['1', '2', '4']], 'b': [['2', '2', '4'], ['1', '2', '4'], ['2', '2', '2']], 'c': [['1', '2', '2'], ['1', '2', '4']]}

using a set allows to keep unicity, but you cannot put a list in a set , so the expression converts to tuple first (which is hashable), and converts back to list once the processing is done. 使用set允许保持唯一性,但是您不能将list放在set ,因此表达式首先转换为tuple (可哈希化),一旦处理完成,则转换回list

In case if order is important , you can use something like this: 如果订单很重要 ,则可以使用以下命令:

results = {'a': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']],
           'b': [['2', '2', '4'],['2', '2', '2'],['1', '2', '4']],
           'c': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']]}

print({k: [y for x, y in enumerate(v) \
     if y not in v[:x]] for k, v in results.items()})

Output : 输出

 {'a': [['1', '2', '4'], ['1', '2', '2']], 
  'b': [['2', '2', '4'], ['2', '2', '2'], ['1', '2', '4']], 
  'c': [['1', '2', '4'], ['1', '2', '2']]} 

To skip first sub-list and require checking only in the remaining, you could do: 要跳过第一个子列表并仅需要检查其余子列表,可以执行以下操作:

print({k: [y for x, y in enumerate(v) \
     if y not in v[1:x]] for k, v in results.items()})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM