Ask Your Question
2

How can one manipulate dictionaries and lists within dictionaries?

asked 2023-07-11 16:24:34 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-11 16:28:02 +0000

lakamha gravatar image

To manipulate dictionaries and lists within dictionaries, you can use various Python methods and operations. Here are some examples:

  1. 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'}
    
  2. 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']}
    
  3. 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']}
    
  4. Accessing values of a list within a dictionary:

    my_dict = {'key1': 'value1', 'key2': ['value2', 'value3']}
    print(my_dict['key2'][0])
    

    Output:

    value2
    
  5. 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
    
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-07-11 16:24:34 +0000

Seen: 10 times

Last updated: Jul 11 '23