Python update a key in dict if it doesn't exist

前端 未结 5 1612
清歌不尽
清歌不尽 2020-12-24 11:17

I want to insert a key-value pair into dict if key not in dict.keys(). Basically I could do it with:

if key not in d.keys():
    d[key] = value
5条回答
  •  旧时难觅i
    2020-12-24 12:04

    With the following you can insert multiple values and also have default values but you're creating a new dictionary.

    d = {**{ key: value }, **default_values}
    

    I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .

    Speed test comparing a for loop based method with a dict comprehension with unpack operator method.

    if no copy (d = default_vals.copy()) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5 and greater. Memory footprint of both methods are the same.

提交回复
热议问题