To manipulate dictionaries and lists within dictionaries, you can use various Python methods and operations. Here are some examples:
Adding a new key-value pair to a dictionary:
my_dict = {'key1': 'value1', 'key2': ['value2', 'value3']}
my_dict['key3'] = 'value4'
my_dict['key2'].append('value4')
print(my_dict)
Output:
{'key1': 'value1', 'key2': ['value2', 'value3', 'value4'], 'key3': 'value4'}
Updating the value of a key in a dictionary:
my_dict = {'key1': 'value1', 'key2': ['value2', 'value3']}
my_dict['key1'] = 'new_value'
my_dict['key2'][0] = 'new_value2'
print(my_dict)
Output:
{'key1': 'new_value', 'key2': ['new_value2', 'value3']}
Removing a key from a dictionary:
my_dict = {'key1': 'value1', 'key2': ['value2', 'value3']}
del my_dict['key1']
my_dict['key2'].remove('value2')
print(my_dict)
Output:
{'key2': ['value3']}
Accessing values of a list within a dictionary:
my_dict = {'key1': 'value1', 'key2': ['value2', 'value3']}
print(my_dict['key2'][0])
Output:
value2
Looping through a dictionary with a list:
my_dict = {'key1': 'value1', 'key2': ['value2', 'value3']}
for key, value in my_dict.items():
if isinstance(value, list):
for item in value:
print(item)
else:
print(value)
Output:
value1
value2
value3
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-11 16:24:34 +0000
Seen: 10 times
Last updated: Jul 11 '23
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?