简体   繁体   English

如何在列表中的字典中检索列表?

[英]How do I retrieve a list within dictionary within a list?

How do I retrieve a list value, within a dictionary, that's within a list? 如何在列表中的字典中检索列表值?

x = [{'name': 'joe', 'items': ['hat','scarf','boots']},
{'name': 'john', 'items': ['jeans','shirt','jacket']}]

x is considered a list type variable, and I'm trying to pull just the values within the list called 'items'. x被认为是列表类型变量,并且我试图仅提取列表中称为“ items”的值。

Calling x[0] will load the first list item which includes name and items for joe, but not sure how to pull only the items. 调用x [0]将加载第一个列表项,该列表项包括joe的名称和项目,但不确定如何仅提取这些项目。 x[0][0] of course doesn't work because it's also part of a dictionary. x [0] [0]当然也不起作用,因为它也是字典的一部分。

你是这个意思吗?:

x[0]['items']

You access it just as you would think intuitively. 您可以像直观地思考那样访问它。 Access the first element in your list, and then the list element at index 0 for your respective dict: 访问列表中的第一个元素,然后访问相应字典的索引0处的list元素:

>>> print(x[0]['items'][0])
hat

The logical progression 逻辑上的进展

>>> print(x[0])
{'name': 'joe', 'items': ['hat', 'scarf', 'boots']}

>>> print(x[0]['items'])
['hat', 'scarf', 'boots']

>>> print(x[0]['items'][0])
hat

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM