如何按值过滤字典?

5 python dictionary

这里有新手问题,所以请耐心等待.

假设我的字典看起来像这样:

a = {"2323232838": ("first/dir", "hello.txt"),
     "2323221383": ("second/dir", "foo.txt"),
     "3434221": ("first/dir", "hello.txt"),
     "32232334": ("first/dir", "hello.txt"),
     "324234324": ("third/dir", "dog.txt")}
Run Code Online (Sandbox Code Playgroud)

我希望将所有彼此相等的值移动到另一个字典中.

matched = {"2323232838": ("first/dir", "hello.txt"),
           "3434221":    ("first/dir", "hello.txt"),
           "32232334":   ("first/dir", "hello.txt")}
Run Code Online (Sandbox Code Playgroud)

其余不匹配的项目应如下所示:

remainder = {"2323221383": ("second/dir", "foo.txt"),
             "324234324":  ("third/dir", "dog.txt")}
Run Code Online (Sandbox Code Playgroud)

在此先感谢,如果您提供示例,请尽可能评论.

Tri*_*ych 10

下面的代码将导致两个变量,matchesremainders. matches是一个字典数组,其中原始字典中的匹配项将具有相应的元素. remainder在您的示例中,将包含包含所有不匹配项的字典.

请注意,在您的示例中,只有一组匹配值:('first/dir', 'hello.txt').如果有多个集合,则每个集合中都有相应的条目matches.

import itertools

# Original dict
a = {"2323232838": ("first/dir", "hello.txt"),
     "2323221383": ("second/dir", "foo.txt"),
     "3434221": ("first/dir", "hello.txt"),
     "32232334": ("first/dir", "hello.txt"),
     "324234324": ("third/dir", "dog.txt")}

# Convert dict to sorted list of items
a = sorted(a.items(), key=lambda x:x[1])

# Group by value of tuple
groups = itertools.groupby(a, key=lambda x:x[1])

# Pull out matching groups of items, and combine items   
# with no matches back into a single dictionary
remainder = []
matched   = []

for key, group in groups:
   group = list(group)
   if len(group) == 1:
      remainder.append( group[0] )
   else:
      matched.append( dict(group) )
else:
   remainder = dict(remainder)
Run Code Online (Sandbox Code Playgroud)

输出:

>>> matched
[
  {
    '3434221':    ('first/dir', 'hello.txt'), 
    '2323232838': ('first/dir', 'hello.txt'), 
    '32232334':   ('first/dir', 'hello.txt')
  }
]

>>> remainder
{
  '2323221383': ('second/dir', 'foo.txt'), 
  '324234324':  ('third/dir', 'dog.txt')
}
Run Code Online (Sandbox Code Playgroud)

作为一个新手,你可能会在上面的代码中介绍一些不熟悉的概念.以下是一些链接:


Avi*_*ion 1

迭代字典与迭代 python 中的列表没有什么不同:

for key in dic:
    print("dic[%s] = %s" % (key, dic[key]))
Run Code Online (Sandbox Code Playgroud)

这将打印字典的所有键和值。