简体   繁体   中英

How can I “map” a dict to change only the values in Python

I have a dict like this:

food_to_food_type = {"apple": "fruit", "green bean": "vegetable", "tomato": "controversial"}

I have a function that wants a dict where keys are food types and values are the number of foods belonging to that type that I want, eg:

num_foods_of_type = {"fruit": 1, "vegetable": 1, "controversial": 1}

In this case, I want an equal number of foods of each type, which I'll represent with a constant.

Is there an easy way to make a new dict by taking the values of my food_to_food_type dict, and using them as keys in my num_foods_of_type dict, setting the values of each to my constant?

Here's the behaviour I want:

NUM_FOODS_DESIRED = 1
num_foods_of_type = {}
for food_type in food_to_food_type.values():
    num_foods_of_type[food_type] = NUM_FOODS_DESIRED

But I want to do this in a functional fashion so I can just transform the food_to_food_type dict on the way into my function:

order_food_types(magic_maplike_function(food_to_food_type.values(), NUM_FOODS_DESIRED))

Of course, I can write magic_maplike_function myself, but surely there must be a Pythonic way to do this, right?

A wonderful solution was proposed here to count the number of occurence in a python list. This can be applied to your case:

values = food_to_food_type.values()
dict( zip( values, map( values.count, values ) ) )

Apparantly, I haven't read your question sufficiently careful. You meant something like this: (?)

values = food_to_food_type.values()
dict( zip( values, [NUM_FOOD_TYPES]*len(values) ) )

You can achieve what you need this way :

dict(zip(food_to_food_type.values(), food_to_food_type.values()*[NUM_FOODS_DESIRED]))
>>> {'vegetable': 1, 'fruit': 1, 'controversial': 1}
>>> help(dict.fromkeys)
Help on built-in function fromkeys:

fromkeys(...)
    dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
    v defaults to None.

Thus,

dict.fromkeys(food_to_food_type.values(), NUM_FOODS_DESIRED)

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