提取嵌套在列表中的字典值



我使用教科书:Python原理基础自学Python3。这一章是——导论:嵌套数据和嵌套迭代。

我正在尝试提取一个嵌套在列表中的字典值。上一个问题要求我从嵌套列表中提取一个项目,这是非常直接的IE:

nested1 = [['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']]
print(nested1[1][0])
d

这个问题要求我做同样的事情,但是要从嵌套在列表中的字典中获取值。

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)

试图解决方案:

print(nested2[2][1])
keyerror: 1

这一个让我接近但不正确。

print([nested2[2]])
[{'b': 3, 'c': 'yes'}]

试图建立在上述部分成功的基础上。

print([nested2[2][1]])
KeyError: 1

在线搜索让我找到了使用的解决方案,但那是几章之外的。我假设这可以在不编写循环的情况下完成。

在Python字典中,关键字是而不是索引,而是冒号左侧的对象-所以你应该写nested2[2]['c']

让我们来分析一下nested2是什么以及如何使用它:

# 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'

希望这能澄清一切!顺便说一下,为了创建这个输出,我使用了iPython,它是python的一个增强的REPL,也是一个优秀的学习和实验工具。编码快乐!

您需要访问第二个字典,因此首先您应该尝试访问[1]的索引,因为索引通常从0开始(因此使用[1]访问第二个字典)。

您可以使用相同的逻辑访问键'c'处的值。

print(nested2[1]['c'])

在dictionary中,您可以使用它们的键访问值。另一方面,您可以使用元素的索引来访问列表中的元素。因此:

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)

输出:

90

最新更新