[英]How to convert a list of dictionaries into a list of each dictionary in the list's values?
I am trying to produce a list of categories that I can pass to my html template to render a nav bar of all the categories. 我正在尝试生成一个类别列表,我可以将其传递到html模板以呈现所有类别的导航栏。 In the products collection in my mongo data base, every product has a category field.
在我的mongo数据库中的产品集合中,每个产品都有一个类别字段。 Using the code below I generate a pymongo cursor of all the categories.
使用下面的代码,我会生成所有类别的pymongo游标。
categories = Database.DATABASE[ProductConstants.COLLECTION].find({}, {'category': True, '_id': False})
print(categories)
<pymongo.cursor.Cursor at 0x1049cc668>
Putting categories in a list gives me 将类别放在列表中给我
categories = list(categories)
print(categories)
[{'category': 'Phones'},
{'category': 'Phones'},
{'category': 'Phones'},
{'category': 'Phones'},
{'category': 'Phones'},
{'category': 'Soaps'}]
This seems to be a step in the right direction. 这似乎是朝正确方向迈出的一步。 I would like the end output for categories to simply be:
我希望类别的最终输出为:
print(categories)
['Phones', 'Soaps'].
I have tried doing this: 我尝试这样做:
categories = [category.values() for category in categories]
print(categories)
[dict_values(['Phones']),
dict_values(['Phones']),
dict_values(['Phones']),
dict_values(['Phones']),
dict_values(['Soaps'])]
If I could get rid of the dict_values I could potentially flatten this list using sum(categories, []) and then put that into a set() such that I don't have any duplicates. 如果我可以摆脱dict_values,则可以使用sum(categories,[])来平整该列表,然后将其放入set()中,这样我就不会有任何重复项。 I believe this would give me the desired result but am not sure how to go about it.
我相信这会给我想要的结果,但不确定如何去做。 Perhaps I am going down the wrong route and there is a better way to go about all of this?
也许我走错了路,并且有更好的方法来解决所有这些问题? Advice would be appreciated.
意见将不胜感激。
It sounds like you need a set of categories: 听起来您需要一组类别:
categories = [{'category': 'Phones'},
{'category': 'Phones'},
{'category': 'Phones'},
{'category': 'Phones'},
{'category': 'Phones'},
{'category': 'Soaps'}]
# use a set to eliminate the duplicate categories
c = set(d['category'] for d in categories)
print(list(c))
Output: 输出:
['Soaps', 'Phones']
Update: 更新:
c = {d['category'] for d in categories} # equivalent using a set comprehension
Try this 尝试这个
categories = Database.DATABASE[ProductConstants.COLLECTION].find({}, {'category': True, '_id': False}).distinct('category')
print categories
This category list will contains the distinct number of category values. 此类别列表将包含不同数量的类别值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.