Print all Unique Values in a Python Dictionary

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)