DenCowboy
DenCowboy

Reputation: 15086

How to print unique dict values in list of dicts

I have a list which look like this:

[{'item1': 'random', 'team': 'team1'},
{'item1': 'blabla', 'team': 'team1'},
{'item1': 'xxx', 'team': 'team2'},
{'item1': 'yyy', 'team': 'team2'},
{'item1': 'zzz', 'team': 'team2'}]

Now I want to print only the unique teams. In this case team1 and team2. What is an efficient way to do this?

Below will print all teams, not only the unique ones.

for item in my_list:
    print(item['team'])

Upvotes: 1

Views: 24

Answers (1)

Tamil Selvan
Tamil Selvan

Reputation: 1749

This can solve your problem,

a = [{'item1': 'random', 'team': 'team1'},
{'item1': 'blabla', 'team': 'team1'},
{'item1': 'xxx', 'team': 'team2'},
{'item1': 'yyy', 'team': 'team2'},
{'item1': 'zzz', 'team': 'team2'}]

unique_teams = list(set([i['team'] for i in a]))

print(unique_teams)

output:

['team1', 'team2']

Let me know if this one helps you,please

Upvotes: 1

Related Questions