nsssayom
nsssayom

Reputation: 374

Adding item to a list nested in a set

I want to add items to a list which is nested in a dictionary (as key-value pair).

I have tried subscribing the dictionary with the desired key and then using the append() and add() method. I now can assign a new list to the dictionary for a specific key using dictionary[key] = [item]. But I need something like this-

G = {'A': ['B', 'C', 'D'],
     'B': ['C', 'F']}

The code I am using right now is-

G = {}
G['A'].append('B')

It gives me the following error-

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'A'

I know how to declare this. But I need help in accessing and appending to the nested list for a specific key of the dictionary.

Upvotes: 0

Views: 52

Answers (1)

Kartikeya Sharma
Kartikeya Sharma

Reputation: 1383

Accessing the list. Say you are accessing the list for key 'A':

lis=G['A']

Appending to the list (Say you want to append 'E' to the lis):

G['A'].append('E')

Upvotes: 1

Related Questions