Is this an acceptable way to smooth out a list of dictons?

I am looking at the right way to smooth something like this

a = [{'name': 'Katie'}, {'name': 'Katie'}, {'name': 'jerry'}]

having

d = {}

Using a dual card:

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 that this can be done better .. not with a list of concepts tho, I feel that what we have is a map to reduce.

+4
source share
6 answers

I do not like your decision because it is difficult to read and has side effects.

For the example data provided by you, using Counter(which is a subclass of the built-in dictionary) is the best approach.

>>> Counter(d['name'] for d in a)
Counter({'Katie': 2, 'jerry': 1})
+8
source

You can use the counter and maintain its functionality:

In [46]: from collections import  Counter

In [47]: from operator import itemgetter

In [48]: Counter(map(itemgetter("name") ,a))
Out[48]: Counter({'Katie': 2, 'jerry': 1})

python 2 itertools.imap:

Counter(itertools.imap(itemgetter("name") ,a))
+4

reduce() , map():

>>> def count_names(d, x):
...     d[x['name']] = d.get(x['name'], 0) + 1
...     return d
...
>>> reduce(count_names, a, {})
{'jerry': 1, 'Katie': 2}
+2

, .

>>> dict(Counter([i['name'] for i in a]))
{'Katie': 2, 'jerry': 1}

Here's a more confusing method using groupby:

from itertools import groupby

>>> dict((name, len(list(totals))) for name, totals in groupby([i["name"] for i in a]))
{'Katie': 2, 'jerry': 1}
+1
source
from collections import defaultdict
val = defaultdict(int)
for names in a:
    val[names['name']] += 1
+1
source

for loop is your friend :)

a = [{'name': 'Katie'}, {'name': 'Katie'}, {'name': 'jerry'}]
result = {}
for data in a:
    if data['name'] not in result:
         result[data['name']] = 0
    result[data['name']] += 1
print result
+1
source

Source: https://habr.com/ru/post/1629794/


All Articles