Reputation: 71
I am self-learning Python3 using the text book: Foundations of Python Principles. The chapter is- Introduction: Nested Data and Nested Iteration.
I am attempting to extract a dictionary value nested inside of a list. The previous question asked me to extract an item from a nested list which was quite straight forward IE:
nested1 = [['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']]
print(nested1[1][0])
d
This question is asking me to do the same but to get the value from a dictionary nested in a list.
nested2 = [{'a': 1, 'b': 3}, {'a': 5, 'c': 90, 5: 50}, {'b': 3, 'c': "yes"}]
#write code to print the value associated with key 'c' in the second dictionary (90)
Attempted solutions:
print(nested2[2][1])
keyerror: 1
This one got me close but not correct.
print([nested2[2]])
[{'b': 3, 'c': 'yes'}]
Attempting to build on partial success above.
print([nested2[2][1]])
KeyError: 1
Searching online leads me to solutions using but that is a few chapters away. I’m making the assumption this can be done without having to write a loop.
Upvotes: 2
Views: 1184
Reputation: 3065
Let's break down what nested2
is and how to use it:
# nested2 is a list of dicts
In [1]: nested2 = [{'a': 1, 'b': 3}, {'a': 5, 'c': 90, 5: 50}, {'b': 3, 'c': "yes"}]
In [2]: type(nested2)
Out[2]: list
# lists are indexable, so if we provide a valid index, starting from 0,
# we can access an element
In [3]: nested2[0]
Out[3]: {'a': 1, 'b': 3}
In [4]: nested2[-1]
Out[4]: {'b': 3, 'c': 'yes'}
In [5]: nested2[-1] is nested2[len(nested2)-1]
Out[5]: True
# when we try to access an index that is longer than the list,
# it throws an Exception (IndexError)
In [6]: nested2[3]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-5-817a2e115204> in <module>
----> 1 nested2[3]
IndexError: list index out of range
# the type of each of nested2's elements is a dict
In [7]: type(nested2[0])
Out[7]: dict
# dicts are accessible by key. the key is the thing to the left
# of the colon, and the value is the thing to the right
In [8]: nested2[0].keys()
Out[8]: dict_keys(['a', 'b'])
In [9]: nested2[0].values()
Out[9]: dict_values([1, 3])
In [10]: nested2[0].items()
Out[10]: dict_items([('a', 1), ('b', 3)])
# so if we want to access a value of some dict, we provide its
# key inside square brackets
In [11]: nested2[0]["a"]
Out[11]: 1
In [12]: nested2[0]["b"]
Out[12]: 3
# when we try to access a key that isn't in the dict,
# it throws an Exception (KeyError)
In [13]: nested2[0]["c"]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-15-69733e9d96af> in <module>
----> 1 nested2[0]["c"]
KeyError: 'c'
Hopefully that clears things up! By the way, to create this output, I used iPython, which is a much enhanced REPL for python and an excellent learning and experimentation tool. Happy coding!
Upvotes: 1
Reputation: 1918
In dictionary you can access the values using their keys. On the other hand, you can use the index of the element to access the element in a list. Hence:
nested2 = [{'a': 1, 'b': 3}, {'a': 5, 'c': 90, 5: 50}, {'b': 3, 'c': "yes"}]
#write code to print the value associated with key 'c' in the second dictionary (90)
target_dictionary = nested2[1] # Here we select the needed dictionary
target_value = target_dictionary['c'] # Then we access the value using its key
print(target_value)
Output:
90
Upvotes: 0
Reputation: 16
You need to access the second dictionary, so to begin with you should attempt to access the index of [1] as indices typically start at 0 (Hence using [1] to access the second dictionary).
You can access the value at the key 'c' by using the same logic.
print(nested2[1]['c'])
Upvotes: 0
Reputation: 365
In a Python dictionary, the keys are not the indices, but rather the objects on the left side of the colon— so you should write nested2[2]['c']
.
Upvotes: 1