简体   繁体   中英

How to iterate over tuples in a dictionary

I need to change a sign from positive to negative within a tuple that's in a dictionary. So if I have 'position: (3,4)' I need to change it to 'position: (3,-4)'. This is what I have but it's not working.

for k,v in positionD.items():
    v = (v[0],-v[1])
    positionNewD[k] = v

Try this (requires Python >= 2.7):

positionNewD = {k: (x, -y) for k, (x, y) in positionD.iteritems()}

For older versions:

positionNewD = dict((k, (x, -y)) for k, (x, y) in positionD.iteritems())

For Python 3

positionNewD = {k: (x, -y) for k, (x, y) in positionD.items()}

... as iteritems() has been renamed items()

http://docs.python.org/3.1/whatsnew/3.0.html#views-and-iterators-instead-of-lists

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