I'm looking at a proper way to flatten something like this
a = [{'name': 'Katie'}, {'name': 'Katie'}, {'name': 'jerry'}]
having
d = {}
Using a double map like this:
map(lambda x: d.update({x:d[x]+1}) if x in d else d.update({x:1}),map(lambda x: x["name"] ,a))
I get the result i want:
>>> d
{'jerry': 1, 'Katie': 2}
But I feel it could be done better..not with list comprehensions tho , I feel that's what we have map reduce.
I don't really like your solution because it is hard to read and has sideeffects.
For the sample data your provided, using a Counter
(which is a subclass of the built-in dictionary) is a better approach.
>>> Counter(d['name'] for d in a)
Counter({'Katie': 2, 'jerry': 1})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With