简体   繁体   中英

Unable to modify the elements of dict in python

I have defined a function called modify which modifies given string. I have a dict called elements which have some strings stored in them. However, I am unable to modify those strings stored in the dict.

x = "abc"
x = modify(x)

This works but when I do;

for element in elements:
    element = modify(element)

This does not work. Any idea why? I'm fairly new to python.

You cannot modify the elements of a dict whilst iterating through them.

You'd need to use something like this:

for key in elements:
    elements[key] = modify(elements[key])

If you need to apply a function to each member of a dictionary, consider using a dict comprehension:

elements = {k: modify(v) for k, v in elements.items()}

If you are using python 2.7 use elements.iteritems() instead of elements.items() .

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