简体   繁体   中英

Pythonic way of updating value in dictionary

I have this current code

lst = [1,2,3,4]
c = dict((el,0) for el in lst)
for key in lst: 
    c[key] += increase_val(key)

Is there a more pythonic way to do it? Like using map? This code words but i would like probably a one-liner or maybe better way of writing this

In my opinion, that is a very clean, readable way of updating the dictionary in the way you wanted.

However, if you are looking for a one-liner, here's one:

new_dict = {x: y + increase_val(x) for x, y in old_dict.items()}

What's different is that this create's a new dictionary instead of updating the original one. If you want to mutate the dictionary in place, I think the plain old for-loop would be the most readable alternative.

In your case no need of c = dict((el,0) for el in lst) statement, because we create dictionary where value of each key is 0 .

and in next for loop you are adding increment value to 0 ie 0 + 100 = 100, so need of addition also.

You can write code like:

lst = [1,2,3,4]
c = {}
for key in lst: 
    c[key] = increase_val(key)

collection.Counter()

Use collections.Counter() to remove one iteration over list to create dictionary because default value of every key in your case is 0 .

Use Collections library, import collections

Demo:

>>> lst = [1,2,3,4]
>>> data = collections.Counter()
>>> for key in lst:
        data[key] += increase_val(key)

collection.defaultdict()

We can use collections.defaultdict also. Just use data = collections.defaultdict(int) in above code. Here default value is zero.

But if we want to set default value to any constant value like 100 then we can use lambda function to set default value to 100

Demo:

>>> data = {}
>>> data["any"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'any'

Get key error because there is on any key in dictionary.

>>> data1 = collections.defaultdict(lambda:0, data)
>>> data1["any"]
0
>>> data1 = collections.defaultdict(lambda:100, data)
>>> data1["any"]
>>> 100

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