return the key whose values are repeated

Viewed 53

I have dictionary whose values of the keys are lists. each list may contain some values repeated more than once like this

{'VSS': ['A2', 'A3', 'A1'], 'X_P1_1': ['A2', 'A1'], 'X_P2': ['A3', 'A2'], 'X_P1_3': ['A2', 'A1'], 'VDD': ['A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'B', 'A3'], 'X': ['B', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'B', 'A1']}

I want to do loop that takes the keys whose values have frequencies more than 1 for example:

VDD: ['A3':8]
X : ['A1':8, 'B':2]

how this can be done?

3 Answers

You could use Counter:

from collections import Counter

data = {'VSS': ['A2', 'A3', 'A1'], 'X_P1_1': ['A2', 'A1'], 'X_P2': ['A3', 'A2'], 'X_P1_3': ['A2', 'A1'], 'VDD': ['A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'B', 'A3'], 'X': ['B', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'B', 'A1']}


result = {key : { e: count for e, count in Counter(values).items() if count > 1}  for key, values in data.items() if any(value > 1 for value in Counter(values).values())}

print(result)

Output

{'VDD': {'A3': 8}, 'X': {'B': 2, 'A1': 8}}

Or if you prefer the values as a list of tuples:

from collections import Counter

data = {'VSS': ['A2', 'A3', 'A1'], 'X_P1_1': ['A2', 'A1'], 'X_P2': ['A3', 'A2'], 'X_P1_3': ['A2', 'A1'],
        'VDD': ['A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'B', 'A3'],
        'X': ['B', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'B', 'A1']}

result = {key: [(element, count) for element, count in counts.items() if count > 1] for key, counts in map(lambda x: (x[0], Counter(x[1])), data.items()) if
          any(count > 1 for count in counts.values())}
print(result)

Output

{'VDD': [('A3', 8)], 'X': [('A1', 8), ('B', 2)]}

Using collections.Counter:

from collections import Counter

# count values in lists, only including counts greater than 1
c = {k: {val: count for val, count in Counter(v).items() if count > 1} \
     for k, v in d.items()}

# isolate only keys where Counter value is non-empty
res = {k: v for k, v in c.items() if v}

{'VDD': {'A3': 8},
 'X': {'B': 2, 'A1': 8}}

The first step is to reverse the mapping.

valuekeydict = {}
for k, vs in orig_dict.items():
    for v in vs:
        valuekeydict.setdefault(v, []).append(v)

Then grab a set of all values where len > 1

result = {v for vs in valuekeydict.values() for v in vs if len(vs) > 1}
Related