简体   繁体   中英

How do I get the unique set of values for a combination of dictionary keys?

I'm using Python 3.7. I have a list of dictionaries, eg

my_dict = [{"a": 1, "b": 5, "c": 6}, {"a": 1, "b": 5, "c": 2}, {"a": 2, "b": 1, "c": 6}]

If I want to get the unique set of values for a single key, eg "a", I can do

set(d['a'] for d in my_dict)

but how would I get the unique set of values for the combination of keys, say "a" and "b"? In the above example, the answer would be

[[1, 2], [1, 5]]

The same way; you just have to iterate over the keys as well.

[set(d[k] for d in my_dict) for k in ["a", "b"]]

I'm not entirely sure about the requirements (unique with respect to what?), but in my interpretation the following works:

> {tuple(d[i] for i in ["a", "b"]) for d in my_dict}
{(1, 5), (2, 1)}

It also does the following:

> my_dict2 = [{"a": 1, "b": 5, "c": 6}, {"a": 5, "b": 1, "c": 2}, {"a": 2, "b": 1, "c": 6}]

> {tuple(d[i] for i in ["a", "b"]) for d in my_dict2}
{(1, 5), (2, 1), (5, 1)}

As opposed to

> [set(d[k] for d in my_dict2) for k in ["a", "b"]]
[{1, 2, 5}, {1, 5}]

The OP asks for something not completely specified, but illustrated with an example. There are, so far, two answer posted. None of them matches the requested example, so I am providing an alternative, which does match the example in the OP.

For the two cases used

my_dict = [{"a": 1, "b": 5, "c": 6}, {"a": 1, "b": 5, "c": 2}, {"a": 2, "b": 1, "c": 6}]   # In the OP
my_dict2 = [{"a": 1, "b": 5, "c": 6}, {"a": 5, "b": 1, "c": 2}, {"a": 2, "b": 1, "c": 6}]   # In one of the answers

the 2 options provided before, plus the current one, give

print([set(d[k] for d in my_dict) for k in ["a", "b"]])         # Answer #1
print({tuple(d[i] for i in ["a", "b"]) for d in my_dict})       # Answer #2
print([list(set(d[k] for d in my_dict)) for k in ["a", "b"]])   # Current Answer

print([set(d[k] for d in my_dict2) for k in ["a", "b"]])        # Answer #1
print({tuple(d[i] for i in ["a", "b"]) for d in my_dict2})      # Answer #2
print([list(set(d[k] for d in my_dict2)) for k in ["a", "b"]])  # Current Answer

[{1, 2}, {1, 5}]
{(1, 5), (2, 1)}
[[1, 2], [1, 5]]           <--- As requested
[{1, 2, 5}, {1, 5}]
{(1, 5), (5, 1), (2, 1)}
[[1, 2, 5], [1, 5]]

You can use the operator itemgetter to fetch multiple values from a dictionary:

from operator import itemgetter

zipped = zip(*map(itemgetter('a', 'b'), my_dict))
list(map(set, zipped))
# [{1, 2}, {1, 5}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM