简体   繁体   中英

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. In the products collection in my mongo data base, every product has a category field. Using the code below I generate a pymongo cursor of all the categories.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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