打印Python字典中的所有唯一值

dva*_*ria 24 python dictionary

我正在努力解决Python中的一个小问题(我的程序现在是3.2.3版本).

我有一个看起来像这样的字典(这只是一个例子,实际上是从这里的另一篇文章中获取的):

[{"abc":"movies"}, {"abc": "sports"}, {"abc": "music"}, {"xyz": "music"}, {"pqr":"music"}, {"pqr":"movies"},{"pqr":"sports"}, {"pqr":"news"}, {"pqr":"sports"}]
Run Code Online (Sandbox Code Playgroud)

我想简单地打印()一个唯一值列表,消除重复.在此列表的末尾,我想在字典中打印唯一值的数量:

movies
sports
music
news

4
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.我发现这里有一些其他的帖子有点相关,但我不太清楚Python是否适用于这个特定的问题.

Ash*_*ary 35

set在此使用,因为它们只包含唯一的项目.

>>> lis = [{"abc":"movies"}, {"abc": "sports"}, {"abc": "music"}, {"xyz": "music"}, {"pqr":"music"}, {"pqr":"movies"},{"pqr":"sports"}, {"pqr":"news"}, {"pqr":"sports"}]
>>> s = set( val for dic in lis for val in dic.values())
>>> s 
set(['movies', 'news', 'music', 'sports'])
Run Code Online (Sandbox Code Playgroud)

循环遍历此集合以获得预期输出:

for x in s:                                
    print x
print len(s)   #print the length of set after the for-loop
... 
movies
news
music
sports
4
Run Code Online (Sandbox Code Playgroud)

这一行s = set( val for dic in lis for val in dic.values())大致相当于:

s = set()
for dic in lis:
   for val in dic.values():
      s.add(val)
Run Code Online (Sandbox Code Playgroud)

  • 那个嵌套列表太疯狂了,**永远**不会想到这一点。 (3认同)
  • 用于解释嵌套列表理解的要点. (2认同)

Joe*_*ein 13

您可以set为此目的展示属性; 每个元素都是唯一的,重复的元素将被忽略.

uniqueValues = set(myDict.values())
Run Code Online (Sandbox Code Playgroud)

通过set这种方式使用,.values()将丢弃从中返回的重复元素.然后,您可以按如下方式打印它们:

for value in uniqueValues:  
    print(value)  
print(len(uniqueValues))
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 9

使用set():

from itertools import chain

unique_values = set(chain.from_iterable(d.values() for d in dictionaries_list))
for value in unique_values:
    print(value)

print(len(unique_values))
Run Code Online (Sandbox Code Playgroud)

.itervalues()在Python 2上使用可以提高效率.因为你有一个字典列表,我们需要先从每个字典中提取出值; 我使用itertools.chain.from_iterable()生成器表达式列出序列中的所有值:

>>> for value in set(chain.from_iterable(d.values() for d in dictionaries_list)):
...     print(value)
... 
news
sports
movies
music
Run Code Online (Sandbox Code Playgroud)

另一种方法是在生成器表达式中使用嵌套循环:

>>> for value in set(v for d in dictionaries_list for v in d.values()):
...     print(value)
... 
news
sports
movies
music
Run Code Online (Sandbox Code Playgroud)


小智 7

dict = {'511':'Vishnu','512':'Vishnu','513':'Ram','514':'Ram','515':'sita'}
list =[] # create empty list
for val in dict.values(): 
  if val in list: 
    continue 
  else:
    list.append(val)

print list
Run Code Online (Sandbox Code Playgroud)