Reputation: 194
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
Upvotes: 0
Views: 1010
Reputation: 4279
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()}
Upvotes: 1