Skip to content Skip to sidebar Skip to footer

Reverse Multiple Values With Keys In Dictionary

I'm quite new to Python and overall programming so bear with me. What I have is a dictionary of ['Male', 'Female', 'Eunuch'] as values and different names for these as keys: Person

Solution 1:

Consider

from collections import Counter

cnt = Counter(lst)
print {gender: {name: cnt[name] for name in persons if persons[name] == gender}
          for gender in set(persons.values())}

# {'Eunuch': {'Varys': 1},# 'Male': {'Tyrion': 3, 'Hodor': 2, 'Theon': 0},# 'Female': {'Daenerys': 2, 'Arya': 1, 'Sansa': 0}}

To calculate percentages let's add a helper function:

def percentage_dict(d):
    s = float(sum(d.values()))
    return {k: 100 * v / s for k, v in d.items()}

and then

print {gender: percentage_dict({name: cnt[name] fornamein persons if persons[name] == gender})
       forgenderinset(persons.values())}

# {'Eunuch': {'Varys': 100.0}, 'Male': {'Hodor': 40.0, 'Theon': 0.0, 'Tyrion': 60.0}, 'Female': {'Daenerys': 66.66666666666667, 'Arya': 33.333333333333336, 'Sansa': 0.0}}

And this is how to write this comprehension more efficiently using a helper function:

definvert(d):
    """Turn {a:x, b:x} into {x:[a,b]}"""
    r = {}
    for k, v in d.items():
        r.setdefault(v, []).append(k)
    return r

and then

cnt = Counter(lst)
print {gender:{name: cnt[name]for name innames}for gender,namesin invert(persons).items()}

To exclude subdicts that sum up to zero

print {gender: {name: cnt[name] for name in names}
    for gender, names in invert(persons).items()
    if any(cnt[name] for name in names)
}

Solution 2:

from collections import defaultdict

gender = {
    'Hodor' : 'Male',
    'Tyrion': 'Male',
    'Theon': 'Male',
    'Arya': 'Female',
    'Daenerys': 'Female',
    'Sansa': 'Female',
    'Varys': 'Eunuch'
}

lst = ['Hodor', 'Hodor', 'Tyrion', 'Tyrion', 'Tyrion', 'Arya', 'Daenerys', 'Daenerys', 'Varys']

result = defaultdict(lambda: defaultdict(int))
for name in lst:
    result[gender[name]][name] += 1

Post a Comment for "Reverse Multiple Values With Keys In Dictionary"