简体   繁体   中英

Add values to dict and increase list item's value by 1 if key is already in dict (python)

Adding values to a dict and using a simple if statement to + 1 to the value if the key exists works fine with the following:

d = {word: (frequency, wordList[1]) for frequency, word in sorteddict}
for key, value in d.items():
    my_dict[key, value] = my_dict[key, value] + 1 if key in my_dict else value

I want to iterate over the dict "d" adding all the key value pairs to the dict "my_dict".

The problem I am having is that the dict's are key : list pairs and I only want to increase the value of list[0] if the key exists. For example:

d = {'smith': (1, 'jones')}

my_dict = {'smith': (2, 'jones')}

my_dict already contains the key 'smith' and so the logic would be:

+ 1 to list[0] else 1

to clarify the question and answer: the problem is that there are 2 dicts d , my_dict . each values is a tuple containing 2 items. what we want is to generate a new dict which has the keys and values of d but with the first item of the value tuple increased by 1 if the key exists in my_dict or set to 1 if it doesn't. we will achieve that like this:

{x: (y[0] + 1 if x in my_dict else 1, y[1]) for x, y in d.items()}

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