Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print all Unique Values in a Python Dictionary

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.

like image 836
dvanaria Avatar asked Jun 20 '13 15:06

dvanaria


People also ask

How do I get unique values in Python?

Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.

How do you count unique values in a dictionary in Python?

The simplest way to count unique values in a Python list is to convert the list to a set considering that all the elements of a set are unique. You can also count unique values in a list using a dictionary, the collections. Counter class, Numpy. unique() or Pandas.


1 Answers

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) 
like image 186
Ashwini Chaudhary Avatar answered Sep 20 '22 23:09

Ashwini Chaudhary