简体   繁体   English

Python:从存储为字典值的列表中调用单个项目

[英]Python: call individual items from a list stored as a dictionary value

How do I access individual items from a list stored as a dictionary value in python?如何从存储为 python 中的字典值的列表中访问单个项目?

my_list = ['black','white']

my_dict = {'black':['yes','no'],'white':['maybe','so']}

I would like to refer to my_list to get values from my_dict .我想参考my_listmy_dict获取值。

print(my_dict[my_list[0]]) returns ['yes', 'no'] . print(my_dict[my_list[0]])返回['yes', 'no']

How do I return just 'yes' or just 'maybe'?我如何返回“是”或“也许”?

Thanks.谢谢。

print(my_dict[my_list[0]][0]) # prints "yes"
print(my_dict[my_list[0]][1]) # prints "no"
print(my_dict[my_list[1]][0]) # prints "maybe"
print(my_dict[my_list[1]][1]) # prints "so"

If you want to use my_list use a for loop:如果你想使用my_list使用 for 循环:

for colour in my_list:
    print(my_dict[colour])

This prints:这打印:

["yes", "no"]
["maybe", "so"]

print(my_dict[my_list[0]][0]) returns the first element from the first dictionary entry value, that is "yes". print(my_dict[my_list[0]][0]) 从第一个字典条目值返回第一个元素,即“是”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python-对字典中存储的列表中的项目进行计数和分组 - Python - count and group items in list stored in dictionary 如何将存储的字典值列表项匹配到单独列表中的项? - How to match dictionary value list items stored to items in a separate list? Python:存储在列表中的字典的增量值 - Python: Increment value of dictionary stored in a list Python:从字典列表中过滤列表项 - Python : filter list items from list of dictionary 如何在python 3.6中获取存储在列表中的字典项 - how to get dictionary items stored in a list in python 3.6 如何使用python从列表中获取字典,将列表条目作为键,并将列表中的项数作为值? - How do I obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python? Python:列表由字典项组成,如果列表中的值也从列表中删除键 - Python: list consist of dictionary items, remove key from list if in list is also it's value Python从项目列表创建字典键 - Python creating dictionary key from a list of items 使用Pymongo将Python字典中的项目作为单个对象编写 - Writing items in Python dictionary as individual objects with Pymongo 形成一个字典,密钥来自列表,value是Python中另一个列表中项目的出现 - Form a dictionary that key is from a list, value is the occurrence of items in another list in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM