Q:

how to append to a dictionary in python

dict = {1 : 'one', 2 : 'two'}
# Print out the dict
print(dict)
# Add something to it
dict[3] = 'three'
# Print it out to see it has changed
print(dict)
4
>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}
4
# to add key-value pairs to a dictionary:

d1 = {
	"1" : 1,
	"2" : 2,
  	"3" : 3
} # Define the dictionary

d1["4"] = 4 # Add key-value pair "4" is key and 4 is value

print(d1) # will return updated dictionary
0
d = {'a': 1, 'b': 2}
print(d)
d['a'] = 100  # existing key, so overwrite
d['c'] = 3  # new key, so add
d['d'] = 4
print(d)
0
case_list = []
for entry in entries_list:
    case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
    case_list.append(case)
0
# Append to Dictionary in Python

# Let's say we had the following dictionary:

languages = {'#1': "Python", "#2": "Javascript", "#3": "HTML"}

# There are two ways to add a key-and-value set to this dictionary

# Number 1: By .update() method

languages.update({"#4": "C#"}) # Adds a #4 key-and-value set

#--------------------------------------------

# Number 2: The define-key method

# This is the easier one

languages['#4'] = 'C#'

# ^^ Just updates a key of #4 to C#, or adds it in this case

0

New to Communities?

Join the community