Home > OS >  How to print unique dict values in list of dicts
How to print unique dict values in list of dicts

Time:04-05

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'])

CodePudding user response:

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

  • Related