user7172
user7172

Reputation: 974

Count values by key in dictionary

I look for something that will count values in dict (automatically)without use a list of element

d = {}

d["x1"] = "1"
{'x1':'1'}

d["x1"] = "2"
{'x1':'2'}

d["x1"] = "3"
{'x1':'3'}

d["x2"] = "1"
{'x1':'3', 'x2':'1'}

ect..

I try create a list them using

for x in list:
    d[x] = list.count(x)

But when I created a list , I receive a memory error

Upvotes: 0

Views: 1580

Answers (3)

siddharthlatest
siddharthlatest

Reputation: 2257

You can use dict in the following manner -

d['x1'] = d.get('x1', 0) + 1

The second argument in get specifies the object to return if the key supplied in the first argument is not found.

Applying this on your example:

from pprint import pprint
d = {}
d['x1'] = d.get('x1', 0) + 1
d['x1'] = d.get('x1', 0) + 1
d['x1'] = d.get('x1', 0) + 1
d['x2'] = d.get('x2', 0) + 1
pprint(d)    # will print {'x1': 3, 'x2': 1}

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174748

Use a defaultdict:

>>> d = defaultdict(int)
>>> d['foo'] += 1
>>> d['foo'] += 1
>>> d['bar'] += 1
>>> for i in d:
...   print i,d[i]
... 
foo 2
bar 1

Upvotes: 1

kennytm
kennytm

Reputation: 523764

Are you sure you want to use a dict to do it? It seems a Counter or a defaultdict suits your need more.

>>> d = collections.Counter()
>>> d['x1'] += 1
>>> d
Counter({'x1': 1})
>>> d['x1'] += 1
>>> d
Counter({'x1': 2})
>>> d['x2'] += 1
>>> d
Counter({'x1': 2, 'x2': 1})

You could also convert a sequence to a counter:

>>> collections.Counter(['x1', 'x1', 'x2'])
Counter({'x1': 2, 'x2': 1})

Upvotes: 3

Related Questions