Home > Blockchain >  How do I check if any key-value pair appears more than once in a list of dictionaries?
How do I check if any key-value pair appears more than once in a list of dictionaries?

Time:01-29

For ex:

people_list = [{"name":"joe", "age":20}, {"name":"tom", "age":35}, {"name":"joe", "age":46}]

How do I check if any key-value pair appears more than once in this list of dictionaries?

I am aware of the counter function.

from collections import Counter

for i in range(len(people_list):
    Counter(people_list[i]["name"])
for key,value in Counter:
    if Counter(key:value) > 1:
        ... 

Just not sure how to make it look and count for a specific key value pair in this list of dictionaries and check if it appears more than once.

CodePudding user response:

You want to collect all the keys from all the contained dictionaries into a single iterable that you can pass to your Counter instance. For this you could use itertools.chain. Then you can use a list comprehension:

from collections import Counter
from itertools import chain

l = [
    {'Booboo': 1},
    {"name":"joe", "age":20},
    {"name":"tom", "age":35},
    {"name":"joe", "age":46}
]

c = Counter(chain.from_iterable(l))
print([k for k in c if c[k] > 1])

Prints:

['name', 'age']

CodePudding user response:

If you want to get as output "joe", because it appears more than once for the key "name", then:

from collections import Counter

people_list = [{"name":"joe", "age":20}, {"name":"tom", "age":35}, {"name":"joe", "age":46}]
counter = Counter([person["name"] for person in people_list])
print([name for name, count in counter.items() if count > 1]) # ['joe']

CodePudding user response:

You can use collections.Counter and update like the below:

from collections import Counter

people_list = [{"name":"joe", "age":20}, {"name":"tom", "age":35}, {"name":"joe", "age":46}]
cnt = Counter()
for dct in people_list:
    cnt.update(dct.items())
print(cnt)

# Get the items > 1
for k,v in cnt.items():
    if v>1:
        print(k)

Output:

Counter({('name', 'joe'): 2, ('age', 20): 1, ('name', 'tom'): 1, ('age', 35): 1, ('age', 46): 1})

('name', 'joe')

CodePudding user response:

You can use a Counter to count the number of occurrences of each value and check if any key-value pair appears more than once.

from collections import Counter

people_list = [{"name":"joe", "age":20}, {"name":"tom", "age":35}, {"name":"joe", "age":46}]

# Count the number of occurrences of each value
counts = Counter(d["name"] for d in people_list)

# Check if any key-value pair appears more than once
for key, value in counts.items():
    if value > 1:
        print(f"{key} appears more than once")

Gives:

joe appears more than once
  • Related