Python 使用键列表从字典中选择值
如何使用列表中的键从字典中获取值 例如,给定一本词典:Python 使用键列表从字典中选择值,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,如何使用列表中的键从字典中获取值 例如,给定一本词典: d = { 'a': 1, 'b': 2, 'c': 3 } >>> d = { ... 'a': 1, ... 'b': 2, ... 'c': 3, ... } >>> L = ['a', 'c'] >>> result = [d[x] for x in L if x in d] >>> result [1, 3] >&g
d = {
'a': 1,
'b': 2,
'c': 3
}
>>> d = {
... 'a': 1,
... 'b': 2,
... 'c': 3,
... }
>>> L = ['a', 'c']
>>> result = [d[x] for x in L if x in d]
>>> result
[1, 3]
>>> for val in result:
... print(val)
...
1
3
和一份清单:
l = ['a', 'c']
我希望输出:
1
3
你可以这样做
print(d[l[0]])
或者为了更具可读性
idx = l[0]
print(d[idx])
您需要循环每个项目以获取所有值,并确保索引存在
如果要检查字典中是否存在给定的密钥,可以执行以下操作:
'a' in d
哪个将返回True,或者
'd' in d
在您的示例中,将返回False。但无论哪种方式,您使用的值都将来自列表中的索引搜索,或者来自您将该值传递给的变量
idx in d
将根据idx中存储的值返回False或True。您可以使用列表理解来选择字典中存在的每个键的值:
d = {
'a': 1,
'b': 2,
'c': 3
}
>>> d = {
... 'a': 1,
... 'b': 2,
... 'c': 3,
... }
>>> L = ['a', 'c']
>>> result = [d[x] for x in L if x in d]
>>> result
[1, 3]
>>> for val in result:
... print(val)
...
1
3
下面是for循环中的答案:
for j in l:
print(d[j])
在这种列表操作方面非常强大:
print([d[x] for x in l])