why does dict.update(key=val) not use the string referenced by key?

python dictionary update if key exists
python update dictionary value list
python update dictionary value by key
python dictionary add value to existing key
python dictionary append
python dict update vs assign
python dictionary keys
store values in dictionary python

As the title suggests, I am trying to update a dictionary using the update() method like in the following code block

for key, val in my_dict.items():
    new_dict.update(key=val)

If my_dict = {'a': 1, 'b': 2} I would expect the result to be that new_dict = {'a': 1, 'b': 2} (assuming of course that new_dict is already defined). However, when executed, I instead get new_dict = {'key': 2}.

What am I doing wrong?

Keyword arguments always use the fixed identifier as the key. Use keyword expansion instead.

new_dict.update(**{key: val})

Or if new_dict really is a dict, just pass the dict itself.

new_dict.update({key: val})

Python Dictionary update(), If the key is in the dictionary, it updates the key with the new value. The syntax of update() is: dict.update([other]). update() Parameters. The update() method takes​  Python Dictionary update() The update() method updates the dictionary with the elements from the another dictionary object or from an iterable of key/value pairs. The update() method adds element(s) to the dictionary if the key is not in the dictionary.

Here is a code for the update method, so you can see why it behaves the way it does (it is not the real source code, just an example):

def update(self, other_dict={}, **kwargs):
    for k, v in other_dict.items():
        self[k] = v
    for k, v in kwargs.items():
        self[k] = v

So if you call new_dict.update(key=val) your kwargs will be equal to {"key": value}.

You need to pass your arguments inside a dictionary if you want to dinamically set the new keys.

Using dictionaries to store data as key-value pairs, The dictionary stores objects as key-value pairs and can be used to represent member of the collection using a key – which can be a human-readable string. a value instead of NoneType value; Use update() to set several key-value pairs at If we pass a dict object into a for-loop, by default, only the key will be yielded: You can only update the value and key cannot be updated. Updating key and value is nothing but removing the key-value pair and adding a new one. Example : Output : So here the key-value pair ‘Apple-20’ is removed and ‘Orange-30’ is added , which is same like updating the ‘Apple-20’ with ‘Orange-30’.

update uses keyword arguments to update dictionary, or dictionary or iterable of pairs. You can just pass your dictionary as the first argument:

new_dict.update(my_dict)

update designed to work with several keys at once. If you just want to set single value, you can just set the value:

new_dict[key] = value

Dictionary Data Structures in Python 3, Each of these values is either a string, Boolean, or integer. Regardless of whether the dictionary is ordered or not, the key-value pairs will remain intact, By making use of dictionaries' key-value pairs, we can reference keys to retrieve values. We can also add and modify dictionaries by using the dict.update() method. However the dict.update function does not quite like it. >>> d = {} >>> d.update(t()) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: dictionary update sequence element #0 has length 3; 2 is required

dict, That includes types like numbers, strings and tuples. Lists and dicts can not be used as keys since they are mutable. Dictionaries in other Constructors¶. dict(): Returns a dictionary object. update: Adds key:value pairs to the dictionary. Yet, so far, I have not found a single such source to also explain WHY it is considered to be bad practice. Does it depend on the programming language? On the underlying framework? On the implementation? Take two simple examples, if it helps: An SQL-like table where rows are indexed by a String primary key. A .NET Dictionary where the keys are

Python Dictionaries, To determine how many items (key-value pairs) a dictionary has, use the len() method. Example. Print the number of items in the dictionary: print(len(thisdict)). Why does __builtins__.dict = DataStore not override the curly brace dictionary constructor? * This is purely for demonstrative purposes. I will not be held responsible for the evil you bring upon this world if you use this code snippet in an actual project.

Not using items() to iterate over a dictionary, For each loop iteration, Python will automatically assign the first variable as the key and the second variable as the value for that key. Anti-pattern¶. The code  I would do something like this : [code]the_dict = {} the_string = 'a=1;b=2;c=3;' for pair in the_string.split(';'): if pair: key, value in pair.split(&#039;=&#039

Comments
  • In new_dict.update(key=val), key isn't your variable, its a named parameter in the keyword arguments in the update method. You can do new_dict.update(my_dict) and skip the for loop.
  • I knew there had to be a simple solution for this! Thank you so much :) I will mark as accepted once the 10 minute delay is passed.
  • Well, I also tried using new_dict.update(dict(key=val)) which gave the same result. Would it have worked if I used a colon instead of an equal?
  • dict(key=val) creates a dictionary {"key": val}, with "key" as a string, that's why it gives you the same value. If you do new_dict.update({key: val}) it will behave as you want.
  • I suppose this would work as well. I initially decided on the loop because I wanted to invoke some conditionals depending on which keys were present in my_dict(for instance if key == 'timepoint': do something)
  • Then you can just use new_dict[key] = value
  • So, are there any benefits to using either update or new_dict[key] = value?
  • They are the same if you are setting single element