简体   繁体   中英

dictionary value operations shortcut

I am wondering why arithmetic operations on dictionary values cannot be shortened with =+ or =- as normal python variables can:

for item in myDict:
    myDict[item] =+ 1

doesn't seem to work, but instead I'm told to use:

for item in myDict:
    myDict[item] = myDict[item] + 1

It doesn't seem very Pythonic to me, but perhaps there is a great explanation for this convention.

The order of the operators is += and -= , not the other way around:

In [31]: my_dict  = {'key1': 1, 'key2': 2}

In [32]: for item in my_dict:
   ....:     my_dict[item] += 1
   ....:

In [33]: my_dict
Out[33]: {'key1': 2, 'key2': 3} # values have been incremented by one

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