A benchmark shows your suspicions of its performance impact appear to be correct:
$ python -m timeit -s 'd = {"key": "value"}' 'd["key"] = "value"'
10000000 loops, best of 3: 0.0741 usec per loop
$ python -m timeit -s 'd = {"key": "value"}' 'd.update(key="value")'
1000000 loops, best of 3: 0.294 usec per loop
$ python -m timeit -s 'd = {"key": "value"}' 'd.update({"key": "value"})'
1000000 loops, best of 3: 0.461 usec per loop
That is, it's about six times slower on my machine. However, Python is already not a language you'd use if you need top performance, so I'd just recommend use of whatever is most readable in the situation. For many things, that would be the [] way, though update could be more readable in a situation like this:
configuration.update(
timeout=60,
host='example.com',
)
…or something like that.
Answer from icktoofay on Stack OverflowA benchmark shows your suspicions of its performance impact appear to be correct:
$ python -m timeit -s 'd = {"key": "value"}' 'd["key"] = "value"'
10000000 loops, best of 3: 0.0741 usec per loop
$ python -m timeit -s 'd = {"key": "value"}' 'd.update(key="value")'
1000000 loops, best of 3: 0.294 usec per loop
$ python -m timeit -s 'd = {"key": "value"}' 'd.update({"key": "value"})'
1000000 loops, best of 3: 0.461 usec per loop
That is, it's about six times slower on my machine. However, Python is already not a language you'd use if you need top performance, so I'd just recommend use of whatever is most readable in the situation. For many things, that would be the [] way, though update could be more readable in a situation like this:
configuration.update(
timeout=60,
host='example.com',
)
…or something like that.
Updating the key directly is thrice as fast, but YMMV:
$ python -m timeit 'd={"k":1}; d.update({"k":2})'
1000000 loops, best of 3: 0.669 usec per loop
$ python -m timeit 'd={"k":1}; d["k"] = 2'
1000000 loops, best of 3: 0.212 usec per loop
Videos
1. You can update many keys on the same statement.
my_dict.update(other_dict)
In this case you don't have to know how many keys are in the other_dict. You'll just be sure that all of them will be updated on my_dict.
2. You can use any iterable of key/value pairs with dict.update
As per the documentation you can use another dictionary, kwargs, list of tuples, or even generators that yield tuples of len 2.
3. You can use the update method as an argument for functions that expect a function argument.
Example:
def update_value(key, value, update_function):
update_function([(key, value)])
update_value("k", 3, update_on_the_db) # suppose you have a update_on_the_db function
update_value("k", 3, my_dict.update) # this will update on the dict
d.update(n) is basically an efficient implementation of the loop
for key, value in n.items():
d[key] = value
But syntactically, it also lets you specify explicit key-value pairs without building a dict, either using keyword argumetns
d.update(a=1, b=2)
or an iterable of pairs:
d.update([('a', 1), ('b', 2)])
I've completed DNA and submitted for full credit using lists instead of dictionaries. DNA was really enthralling to me for some reason and I'm going back and trying to make my code both more pythonic and attempting to get it better optimized. Part of my motivation is that I just don't feel anywhere near as comfortable with dictionaries as I did coming out of previous weeks' psets that had similar, heavier (for me) concepts.
One specific area that's giving me trouble in my understanding is the .update() method. I'm using it to store the small.csv info into a dict named STR. I had thought it was the analogue of .append() for lists but, after trying to incorporate it into my revamped DNA, it will update for the first row of the CSV being read on the first iteration but then it just continually replaces that single row/entry in the dict with each iteration. I'm sure I'm just not grasping something fundamental about dicts and/or update() but am not knowledgeable enough yet to know what that might be. I'm not even sure it's technically necessary to be storing the database csv or if it's better to work with the CSV in-place.
Could someone please help me understand why my expectation of update() is flawed?
The code below only stores the last line of the small.csv database:
{'name': 'Charlie', 'AGATC': '3', 'AATG': '2', 'TATC': '5'}
# Open person STR profiles csv and append to STR list
with open(sys.argv[1], 'r', newline = '') as file:
reader = csv.DictReader(file)
for row in reader:
STR.update(row)Hallo Team,
I want to update a json file which no less than 100 values.
Here is short example, I wish to update the values in this json file
{
"skipEsxThumbprintValidation": true,
"managementPoolName": "pool-md-vcf0-ko",
"sddcManagerSpec": {
"hostname": "sddc-md-vcf0-ko",
"ipAddress": "172.16.18.59",
"netmask": "255.255.255.0",
"localUserPassword": "YouknowBetter!",
"rootUserCredentials": {
"username": "root",
"password": "YouknowBetter!"
},
"secondUserCredentials": {
"username": "vcf",
"password": "YouknowBetter!"
}
},my code looks like below
# Purpose: read the json template and create a new bringup file out of it
import json
bringup_template = "vcf51_bring_template.json"
with open(bringup_template, "r") as f:
template_data = json.load(f)
sddcspecs = template_data.get("sddcManagerSpec")
sddcspecs["hostname"] = "test"
sddcspecs["ipAddress"] = "someip"
sddcspecs["netmask"] = "somedata"
sddcspecs["localUserPassword"] = "something"
sddcspecs["rootUserCredentials"] = "something"
sddcspecs["secondUserCredentials"] = "something"
template_data.update(sddcspecs)
print(template_data)I was wondering if there is better approach to update this dictionary. The above is a very small snippet of json file. I have minimum 100 values to update. I see this is literally typing all things without much logic.
Is there a better approach?
I just learned about the update method while doing some work. I had been writing if statements to check if key is in .keys() for so long. Is there an equivalent for "add key: value if not already in dictionary, otherwise update the value"?
For example to replace:
if ind in collection.keys(): collection[ind].append(x) else: collection[ind] = [x]