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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With