简体   繁体   中英

How do I apply the same function to each value in an array of dicts?

I'm using Python 3.7. I have an array of dicts, each array having the same keys. For example

arr_of_dicts = ({"st" : "il"}, {"st" : "IL"}, {"st" : "Il"})

How do I apply the same function to a certain key's value in each dict? For example, I would like to apply the uppercase function to the value making the above

arr_of_dicts = ({"st" : "IL"}, {"st" : "IL"}, {"st" : "IL"})

?

Using map() , you can make your transformation function accept a key to transform and return a lambda, which acts as the mapping method. By using the previously passed key ( k ) and the passed in dictionary ( d ), you can return a new dictionary with the dictionary's value converted to uppercase:

arr_of_dicts = ({"st" : "il"}, {"st" : "IL"}, {"st" : "Il"})

upper = lambda k: lambda d: {k: d[k].upper()} # your func
res = map(upper('st'), arr_of_dicts) # mapping method

print(list(res))

Result:

[{'st': 'IL'}, {'st': 'IL'}, {'st': 'IL'}]

If your dictionaries have additional keys, then you can first spread the original dictionary into your new dictionary, and then overwrite the key propery you want to transform with the uppercase version like so:

arr_of_dicts = [{"a": 5, "st" : "il"}, {"a": 7, "st" : "IL"}, {"a": 8, "st" : "Il"}]

upper = lambda k: lambda d: {**d, k: d[k].upper()}
res = map(upper('st'), arr_of_dicts) # mapping method

print(list(res))

Result:

[{'a': 5, 'st': 'IL'}, {'a': 7, 'st': 'IL'}, {'a': 8, 'st': 'IL'}]

You might also like pandas.

If you do a lot of stuff like this, you should check into pandas and its apply functionality . It can make these sorts of things as quick as:

df = df.apply(your_func)

It's a really powerful tool and you can sometimes make some slick and handy one-liners if that's your kind of thing.

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