skps
0
Q:

python how to add a new key to a dictionary

d = {'key':'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'mynewkey': 'mynewvalue', 'key': 'value'}
21
dict[key] = value
14
# Basic syntax:
dictionary['new_key'] = value

# Example:
d = {'a': 1, 'b': 5} # Define dictionary
d['c'] = 37 # Add a new key to the dictionary
print(d)
--> {'a': 1, 'b': 5, 'c': 37}
1
>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}
4
d = {'key': 'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'key': 'value', 'mynewkey': 'mynewvalue'}
0
dict = {'key1':'addme', 'key2':'fill_me'} 
print("Current Dict is: ", dict) 
  
# using the subscript notation 
# Dictionary_Name[New_Key_Name] = New_Key_Value 
dict['key2'] = 'for'
dict['key3'] = 'newtask'
print("Updated Dict is: ", dict) 
-1

New to Communities?

Join the community