Well you can simply use:
d['word'] = [1,'something']
Or in case the 1 needs to be fetched:
d['word'] = [d['word'],'something']
Finally say you want to update a sequence of keys with new values, like:
to_add = {'word': 'something', 'word1': 'something1'}
you could use:
for key,val in to_add.items():
if key in d:
d[key] = [d[key],val]
Answer from willeM_ Van Onsem on Stack OverflowWell you can simply use:
d['word'] = [1,'something']
Or in case the 1 needs to be fetched:
d['word'] = [d['word'],'something']
Finally say you want to update a sequence of keys with new values, like:
to_add = {'word': 'something', 'word1': 'something1'}
you could use:
for key,val in to_add.items():
if key in d:
d[key] = [d[key],val]
You could write a function to do this for you:
>>> d = {'word': 1, 'word1': 2}
>>> def set_key(dictionary, key, value):
... if key not in dictionary:
... dictionary[key] = value
... elif type(dictionary[key]) == list:
... dictionary[key].append(value)
... else:
... dictionary[key] = [dictionary[key], value]
...
>>> set_key(d, 'word', 2)
>>> set_key(d, 'word', 3)
>>> d
{'word1': 2, 'word': [1, 2, 3]}
Alternatively, as @Dan pointed out, you can use a list to save the data initially. A Pythonic way if doing this is you can define a custom defaultdict which would add the data to a list directly:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d[1].append(2)
>>> d[2].append(2)
>>> d[2].append(3)
>>> d
defaultdict(<type 'list'>, {1: [2], 2: [2, 3]})
How to add new values to existing dictionary in python - Stack Overflow
How do you add to a value in a dictionary?
way to add a key and append new value to dictionary of lists?
Adding new values to existing keys in nested dictionary
Videos
You create a new key/value pair on a dictionary by assigning a value to that key
Copyd = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.
I feel like consolidating info about Python dictionaries:
Creating an empty dictionary
Copydata = {}
# OR
data = dict()
Creating a dictionary with initial values
Copydata = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}
Inserting/Updating a single value
Copydata['a'] = 1 # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)
Inserting/Updating multiple values
Copydata.update({'c':3,'d':4}) # Updates 'c' and adds 'd'
Python 3.9+:
The update operator |= now works for dictionaries:
Copydata |= {'c':3,'d':4}
Creating a merged dictionary without modifying originals
Copydata3 = {}
data3.update(data) # Modifies data3, not data
data3.update(data2) # Modifies data3, not data2
Python 3.5+:
This uses a new feature called dictionary unpacking.
Copydata = {**data1, **data2, **data3}
Python 3.9+:
The merge operator | now works for dictionaries:
Copydata = data1 | {'c':3,'d':4}
Deleting items in dictionary
Copydel data[key] # Removes specific element in a dictionary
data.pop(key) # Removes the key & returns the value
data.clear() # Clears entire dictionary
Check if a key is already in dictionary
Copykey in data
Iterate through pairs in a dictionary
Copyfor key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys
Create a dictionary from two lists
Copydata = dict(zip(list_with_keys, list_with_values))
TL;DR: You can append a value to a Python list (or array), but not to a dictionary.
Add key: value pair to dictionary
The syntax dictionary[key] = message1 changes the existing value of dictionary[key] to message if the key is already in the dictionary, and creates a key-value pair key: message1 if the key is not yet in the dictionary.
So instead of this...
Copyif key in dictionary:
dictionary[key].append(message1)
else:
dictionary[key] = message1
...you would use this:
Copydictionary[key] = message1
Update dictionary with different key: value pairs
If you want to update a dictionary with the values from another dictionary, you can do it this way:
Copydictionary_1.update(dictionary_2)
This modifies dictionary_1 in place, using the values for each key in dictionary_2.
If a key does not exist in dictionary_1, but exists in dictionary_2, then update will modify dictionary_1 based on dictionary_2, so that dictionary_1 includes the key-value pair key: dictionary_2[key].
Or, if a key exists in both dictionary_1 and dictionary_2, then update will overwrite the existing value in dictionary_1[key] with the value from dictionary_2[key].
So instead of this...
Copyif key in dictionary:
dictionary[key].append(message1)
else:
dictionary[key] = message1
...you would use this:
Copydictionary[key].update(message1)
This works only if the value of dictionary[key] is a dictionary.
Append values to list within dictionary
If you want a key to have multiple values, you can store the multiple values in a list:
Copydictionary = {key: [value_1, value_2, value_3]}
Then you can append another value to the list:
Copydictionary[key].append(value_4)
Result:
Copydictionary = {key: [value_1, value_2, value_3, value_4]}
So instead of this...
Copyif key in dictionary:
dictionary[key].append(message1)
else:
dictionary[key] = message1
...you would use this:
Copyif key in dictionary:
dictionary[key].append(message1)
else:
dictionary[key] = [message1]
If key already exists in dictionary, this appends message to dictionary[key]. Otherwise, it creates a new single-item list [message1] as the value of dictionary[key].
However, dictionary[key].append(message1) only works if the value of dictionary[key] is a list, not if the value is a dictionary.
You should be using a list to store these values. There's no reason to have nested dicts here. Especially since you're just using append here.
Your data would then look like this:
Copydata = {
"key1":["value1-1", "value1-2","value1-3"],
"Key2":["value2-1","value2-2", "value2-3"]}
Then you won't need an if statement just use dict.setdefault
Copydata.setdefault(key, []).append(message)
I know how to update values in a dictionary. That's easy, and there are multiple ways to do it. However, what I'm looking for is how to add to a value in a dictionary. For example:
def frequency_dictionary(words):
new_dict = {}
for word in words:
if word not in new_dict:
new_dict[word] = 1
else:
#?????
return new_dictI want this function to add 1 to the value of a word for each time it is featured in the words list. For example, print(frequency_dictionary(["apple", "apple", "cat", 1])) should return {"apple":2, "cat":1, 1:1}. The comment in the function with question marks is the part I am stuck on. What are some options to do this?
I tried looking this up, but all I got was info on how to update values, not add to them.