Reputation: 16469
I have a data set that is a list of dictionaries that have a value of a list.
ex:
a =
[
{'node1':[1,2,3]},...,..
]
I was wondering how can I access the 1 or 2 inside node1
? I know that if I did a[0][0] I would display {'node1':[1,2,3]}. I thought a[0][0][0]
would display 1 but I am getting the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
Upvotes: 2
Views: 103
Reputation: 2204
a = [ {'node1':[1, 2, 3]} ]
>>> a[0]['node1'][0]
a[0] selects the first element in the list which is the map {'node1': [1, 2, 3]}. Then a[0]['node1'] selects the value of the map with key 'node1'. Finally a[0]['node1'][0] selects the first element from the list which is the value for the key from map. This gives 1.
for getting the value 2
>>> a[0]['node1'[1]
Change the index accordingly.
Upvotes: 1
Reputation: 4319
a[number]
is one of your dictionaries, i.e. {'node1': [1, 2, 3], 'node2': [4, 5, 6]}
.
Now, a[number]['node1']
returns the list belonging to 'node1'
, i.e. [1, 2, 3]. You can access the list normally.
So the complete expression would be
a[0]['node1'][0]
>>> 1
Upvotes: 4
Reputation: 1758
Try a[0]['node1'][0]
. You can refer to an item in dict by its key (which is 'node1' in your case). Indexes like [0] do not make sense in dictionaries, as their items don't have a specified order.
Note that your a[0][0]
example should also result an error. a[0] is what returns the first dict in your list: {'node1':[1,2,3]}
Upvotes: 3
Reputation: 22882
You need to index into the dictionary using the name of the key, in this case 'node1'
:
>>> a = [{'node1':[1,2,3]}]
>>> a[0]['node1'][0]
1
Upvotes: 3