Cannot rename Python dict key values with pop - Bug?

python rename key in list of dicts
rename all keys in dictionary python
python dictionary
change value of key in dictionary python
rename keys dict
python dictionary pop
rename key in object python
how to change the value of a key python

I cannot rename the Python dict using pop as described below. I've used suggestions from this post. Is this a Python bug? I'm using Python 3.5.2

>>> d = {'a': 'ABC', 'b': 'CDE', 'c': 'KRT'}
>>> for old_key in d.keys():
        d['NEW_KEY_' + old_key] = d.pop(old_key)
>>> d

{'NEW_KEY_NEW_KEY_NEW_KEY_b': 'CDE', 'NEW_KEY_NEW_KEY_a': 'ABC', 'c': 'KRT'}

In Python 3, you have to change for old_key in d.keys() into for old_key in list(d.keys()). That should work because you are iterating over a dynamic entity.

Rename a key in dict, Suppose we want to change the key but retain the value it holds, how to do this? dictionary[new_key] = dictionary.pop(old_key) How can I rename a file in Python? We cannot. Post-Graduate Program in Artificial Intelligence & Machine Learning · Post-Graduate Program in Big Data Engineering  here's a tight little function: def keys_swap(orig_key, new_key, d): d[new_key] = d.pop(orig_key) for your particular problem: def append_to_dict_keys(appendage, d): #note that you need to iterate through the fixed list of keys, because #otherwise we will be iterating through a never ending key list!

It's mentioned in the documentation that changing a dictionary while iterating over it might fail to produce correct results. You'd better write something like

new_dict = {'NEW_KEY_' + key: value for key, value in old_dict.items()}

How to rename a dictionary key in Python, pop(key) to remove an old key from dict and return its value. With the same dictionary, assign a new dictionary key to this value. a_dict = {"a"  WeakValueDictionary.setdefault() contains a bug that shows up in multithreaded situations using reference cycles. Attached a test case: it is possible for 'setdefault(key, default)' to return None, although None is never put as a value in the dictionary. (Actually, being a WeakValueDictionary, None is not allowed as a value.)

You are changing your keys as you iterate over a view of them. That's not recommended.

Instead, you can take a copy of your keys and iterate over them. Since dictionary keys are unique, you can use list or set:

d = {'a': 'ABC', 'b': 'CDE', 'c': 'KRT'}

for old_key in list(d):
    d['NEW_KEY_' + old_key] = d.pop(old_key)

# {'NEW_KEY_a': 'ABC', 'NEW_KEY_b': 'CDE', 'NEW_KEY_c': 'KRT'}

You can, of course, use a dictionary comprehension, which you should find more efficient.

8.3. collections — Container datatypes, deque, list-like container with fast appends and pops on either end It is an unordered collection where elements are stored as dictionary keys 'g']) >>> d.​clear() # empty the deque >>> d.pop() # cannot pop from an empty If rename is true, invalid fieldnames are automatically replaced with positional Found a bug​? The pop () method removes and returns an element from a dictionary having the given key. The syntax of pop () method is. dictionary.pop (key [, default]) pop () Parameters. The pop () method takes two parameters: key - key which is to be searched for removal. default - value which is to be returned when the key is not in the dictionary.

8.3. collections — High-performance container datatypes, It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. 'j', 'i', 'h', 'g']) >>> d.clear() # empty the deque >>> d.pop() # cannot pop from an empty deque If rename is true, invalid fieldnames are automatically replaced with positional names. Found a bug? In this article we will discuss diiferent ways to delete a key from dictionary in python. Suppose we have a dictionary of string and int i.e. Now we want to remove an item from dictionary whose key is “at”. Let’s see how to do that, del statement removes the given item from the dictionary. If given key is not present in dictionary then it

collections — Container datatypes, list-like container with fast appends and pops on either end It is a collection where elements are stored as dictionary keys and their counts are stored as  You can associate the same value with many keys, or just remove a key and re-add a new key with the same value. For example, if you have keys->values: red->1 blue->2 green->4

What's New, Window functions are now methods; Changes to rename; Range Index; Changes to str. Bug in Series.clip() and DataFrame.clip() cannot accept list-like threshold dict insertion order for python 3.6+; Deprecate Panel; pandas.core.common Series.fillna() now accepts a Series or a dict as a value for a categorical dtype  mapper dict-like or function. Dict-like or functions transformations to apply to that axis’ values. Use either mapper and axis to specify the axis to target with mapper, or index and columns. index dict-like or function. Alternative to specifying axis (mapper, axis=0 is equivalent to index=mapper). columns dict-like or function

Comments
  • I don't understand what you think is buggy behaviour here?
  • @roganjosh presumabley the fact that 'NEW_KEY_NEW_KEY_NEW_KEY_b' exists as does 'c'
  • @FHTMitchell You're probably right. It's still not buggy, it's just more fuel for the argument of not changing something while iterating over it :)
  • For what it's worth, I'm unable to reproduce this in a Docker python:3.5.2 container (it is reproable in 3.4.9).
  • This needs a bit more explanation IMO. How dict.keys() is a view and why you shouldn't mutate something you are iterating over.
  • You are welcome to update the answer. Ironically, the code posted in the question works for me already ;-)
  • This would be better, yes, unless the OP actually does need to modify the original dictionary in-place.
  • @AKX: in that case, he can just replace it. old_dict = {...}
  • No, that just assigns a new value to the name old_dict. It's not the same as mutating the original dictionary.
  • Nice solution as well. Works perfectly.
  • @roganjosh, Don't see why not. Do you see a problem with this? The important thing is you aren't iterating over a view.
  • So the dictionary comprehension is the recommended method. But not everyone is comfortable with them. Where performance isn't a concern a regular for loop with pop is entirely fine.