Reputation: 974
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
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
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
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