To append a key-value pair to a dictionary in Python, use square bracket notation (dict[key] = value). This method adds a new key with the specified value or updates the value if the key already exists.
For example:
my_dict = {'name': 'Alice', 'age': 25}
my_dict['city'] = 'New York'
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}Other common methods:
update(): Add multiple key-value pairs at once.my_dict.update({'email': '[email protected]', 'job': 'Engineer'})setdefault(): Add a key only if it doesnโt exist.my_dict.setdefault('country', 'USA')Dictionary unpacking (
**): Create a new dictionary with merged values (Python 3.5+).new_dict = {**my_dict, 'phone': '123-456-7890'}Union operator (
|): Merge dictionaries (Python 3.9+).merged = my_dict | {'salary': 50000}
Use square bracket notation for single additions, update() for multiple pairs, and setdefault() to avoid overwriting existing keys.
You create a new key/value pair on a dictionary by assigning a value to that key
d = {'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.
Answer from Paolo Bergantino on Stack OverflowYou create a new key/value pair on a dictionary by assigning a value to that key
d = {'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
data = {}
# OR
data = dict()
Creating a dictionary with initial values
data = {'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
data['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
data.update({'c':3,'d':4}) # Updates 'c' and adds 'd'
Python 3.9+:
The update operator |= now works for dictionaries:
data |= {'c':3,'d':4}
Creating a merged dictionary without modifying originals
data3 = {}
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.
data = {**data1, **data2, **data3}
Python 3.9+:
The merge operator | now works for dictionaries:
data = data1 | {'c':3,'d':4}
Deleting items in dictionary
del 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
key in data
Iterate through pairs in a dictionary
for 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
data = dict(zip(list_with_keys, list_with_values))
Videos
I am currently using a while loop to loop and get certain values. I then want to append these values to a dictionary. Every loop through I want to append to two keys
General structure of the code: https://pastebin.com/p4hJcKR5
I have tried using:
dict[key] = value
dict.append(value)
And neither have worked, dict.append gives an error and dict[key] just sets the dictionary to the most recent iteration instead of iterating for all values. Any help would be appreciated.
As the error states, dict has no attribute append. There is no append method in the dictionary object. To assign a value to a particular key in a dictionary, it is simply:
d[key] = new_value
where new_value can be, if you wish: {'a':1}
If you are looking to update your dictionary with new data, you can use the update method.
d.update(new_stuff)
In your code, simply change your append, similar to the example I provided. I corrected it here:
crucial = {'C': {'C': 0, 'B': 1}}
done = {}
for each in crucial:
for i in each:
done['D'] = 0
print(done)
crucial[i].update(done)
print(crucial)
Python has a update function to add new items to dictionary
crucial .update({'D':'0'})