打印Python字典中的所有唯一值 [英] Print all Unique Values in a Python Dictionary
问题描述
我有一个看起来像这样的字典这只是一个例子,实际上是从另一篇文章中获取的):
[{abc:movies},{ abc:sports},{abc:music},{xyz:music},{pqr:music},{pqr pqr:sports},{pqr:news},{pqr:sports}]
我想简单地打印()一个唯一值的列表,消除重复。在这个列表的最后,我想打印字典中唯一值的数量:
电影
运动
音乐
新闻
4
任何帮助是赞赏。还有一些其他的帖子,我发现这是有些相关的,但我不知道Python足够好地应用到这个具体问题。
使用设置
,因为它们只包含唯一的项目。
>>> lis = [{abc:movies},{abc:sports},{abc:music},{xyz:music},{pqr },{pqr:movies},{pqr:sports},{pqr:news},{pqr:sports}]
>> ;> s = set(对于dic.values()中的val的dic的val)val
>>>> s
set(['movies','news','music','sports'])
循环此集合以获取预期的输出:
for x in s:
print x
打印len(s)#print循环后设置的长度
...
电影
新闻
音乐
运动
4
此行 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)
I'm struggling with a minor problem in Python (my program is in version 3.2.3 right now).
I have a dictionary that looks like this (this is just an example, actually taken from another post here):
[{"abc":"movies"}, {"abc": "sports"}, {"abc": "music"}, {"xyz": "music"}, {"pqr":"music"}, {"pqr":"movies"},{"pqr":"sports"}, {"pqr":"news"}, {"pqr":"sports"}]
I want to simply print() a list of unique values, eliminating duplicates. At the end of this list, I would like to print the number of unique values in the dictionary:
movies
sports
music
news
4
Any help is appreciated. There are some other posts here I found that were somewhat related, but I don't know Python well enough to apply it to this specific problem.
Use set
here as they only contain unique items.
>>> 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'])
Loop over this set to get the expected output:
for x in s:
print x
print len(s) #print the length of set after the for-loop
...
movies
news
music
sports
4
This line s = set( val for dic in lis for val in dic.values())
is roughly equivalent to:
s = set()
for dic in lis:
for val in dic.values():
s.add(val)
这篇关于打印Python字典中的所有唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!