In this post, I am going to explain how to add a list to the dictionary.
list_in_dictionary.py
dict = {1 : "One"}
even_numbers = [2, 4, 6, 8]
odd_numbers = [1, 3, 5, 7]
my_dictionary = {"dict": dict, "evenNumbers" : even_numbers, "oddNumbers" : odd_numbers}
for key in my_dictionary.keys():
print(f"{key} -> {my_dictionary[key]}")
This Python snippet initializes three separate variables: a dictionary named dict with the key-value pair {1: "One"}, a list named even_numbers containing even integers [2, 4, 6, 8], and another list named odd_numbers containing odd integers [1, 3, 5, 7]. Subsequently, a new dictionary named my_dictionary is created, where each key corresponds to a different variable, linking the names 'dict', 'evenNumbers', and 'oddNumbers' to their respective values.
The snippet then employs a for loop to iterate through the keys of my_dictionary. Within each iteration, it prints a formatted string indicating the key and its associated value. This loop effectively showcases the contents of my_dictionary by displaying each key-value pair.
Output
$ python3 list_in_dictionary.py
dict -> {1: 'One'}
evenNumbers -> [2, 4, 6, 8]
oddNumbers -> [1, 3, 5, 7]
No comments:
Post a Comment