Reputation: 2850
I have a python dictionary where the value is a 2 item list. The first item is a count of how many times I have seen the key. The 2nd item is another integer which I need to update based on some input.
dictionary = {
'key1' : [1, 200]
'key2' : [1, 100]
}
Suppose, I encounter key1
again and the input is 150
. So the update operation should yield
dictionary = {
'key1' : [2, 350]
'key2' : [1, 100]
}
How do I do it? I saw this post but doesn't help. Please suggest. I am using Python 3.
EDIT:
Before posting this, I tried below:
data = defaultdict(list)
key = requestTokens[1] # one of the input that works as a key
data[key][0] +=1
data[key][1] += int(statusTokens[1]) #another input is statusTokens[1] a string
But I am getting error
data[key][0] +=1
IndexError: list index out of range
Upvotes: 0
Views: 2081
Reputation: 740
>>> di = {'key1': [1,200], 'key2':[1,100]}
>>> di
{'key1': [1, 200], 'key2': [1, 100]}
>>> di['key1'][0] += 1
>>> di['key1'][1] += 150
>>> di
{'key1': [1, 300], 'key2': [1, 100]}
>>>
So looking at the above example you can see that it is first accessing the key then the index in the array and setting it to a new value.
di['key1'][0] += 1
is incrementing it by 1
di['key1'][1] += 150
is adding the new value
Upvotes: 3