简体   繁体   中英

Python: Populate or add value to current value in a dictionary

I have data in the form of

00 154
01 72
02 93
03 202
04 662
05 1297
00 256

I wish to go through each line and make the value in column 1 the key and the value of column 2 the value

also if the current key already exists, mathematically add the new value of column 2 to the current value of column 2.

Tried this:

search_result = searches.stdout.readlines()
      for output in search_result:
        a,b =  output.split()
        a = a.strip()
        b = b.strip()

        if  d[a]:
         d[a] = d[a] + b
        else:
         d[a] = b

And Got this:

Traceback (most recent call last):
  File "./get_idmanager_stats.py", line 25, in <module>
    if  d[a]:
KeyError: '00'

This is what collections.defaultdict is for.

You can simply do

d = defaultdict(int)

And

d[a]= d[a] + int(b)

And you'll find that it works without any if statement.

d = collections.defaultdict(int)
for output in search_results:
   a,b = output.split()
   d[int(a)] += int(b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM