简体   繁体   中英

How to create a frequency dictionary with list of values in python 3.6

I am trying to write a function in python 3.6 that returns a dictionary with item count being the key and a list of items that have that count.

Here is an example of what a test case should look like: Input: {'x':3, 'y':3, 'z':100} Output: {3: ['x', 'y'], 100: ['z']}

This is what I have for code so far:

def get_count_items(key_count):
    # create blank dictionary
    count_items = {}
    #for each item_key in key_count:
    for item_key in key_count
    # retrieve its value (which is a count)
    # if the count (as key) exists in count_items:
    if item in count_items:
        count_items[item] += 1
    # append the item_key to the list
    # else:
    #add the count:[item_key] pair to count_items dictionary
    else:
        count_items[item] = 1

    for key, value in count_items.items():
    #return count_items dictionary
        return count_items

My questions here are how can I set each of the count values as keys, and how can I make a corresponding list of each item that has that count?

Thanks for the help!

from collections import defaultdict

d = {'x':3, 'y':3, 'z':100} 

# create defaultdict with list type. 
res = defaultdict(list)

# iterate over key value pair
for k, v in d.items():
    res[v].append(k)
print(res)
# or
print(dict(res))

output:

defaultdict(<class 'list'>, {3: ['x', 'y'], 100: ['z']})
{3: ['x', 'y'], 100: ['z']}

Try this:

a = {'x':3, 'y':3, 'z':100}
d = {}
for x in a:
    if a[x] in d:
        d[a[x]].append(x)
    else:
        d[a[x]]=[x]
print(d)

for the sake of a different approach..you can do this in pandas pretty easily:

import pandas as pd
df = pd.DataFrame([in_dict]).T
df['vars'] = df.index
out_dict = df.groupby(0)['vars'].agg(list).to_dict()

output:

{3: ['x', 'y'], 100: ['z']}

there's probably a way around having a separate line to initialize df['vars'], or maybe not needed at all but couldn't get it to work otherwise

EDIT - maybe a bit less pretty, but shorter:

df = pd.DataFrame({'vals':[*in_dict.values()],'vars':[*in_dict.keys()]})
out_dict = df.groupby('vals')['vars'].agg(list).to_dict()

try this:

d = {'x':3, 'y':3, 'z':100} 
x={}
for key, value in sorted(d.items()): 
    x.setdefault(value, []).append(key) 

x
{3: ['x', 'y'], 100: ['z']}

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