Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an acceptable way to flatten a list of dicts?

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.

like image 627
Jeronimo Garcia Avatar asked Dec 02 '22 15:12

Jeronimo Garcia


1 Answers

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})
like image 136
timgeb Avatar answered Dec 28 '22 01:12

timgeb