Reputation: 19150
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"})
?
Upvotes: 1
Views: 1049
Reputation: 50759
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'}]
Upvotes: 2
Reputation: 119
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.
Upvotes: 0