Reputation: 560
I have a list of dictionary in my variable , as shown below :
category = [ { "S" : "Restaurants" }, { "S" : "Drinks" }, { "S" : "Outdoor Seating" }]
I want to remove keys and it should just give me values , output should look like :
[Restaurants,Drinks,Outdoor Seating]
Note : that length of list is varying everytime , lets say above category variable has 3 key-value pairs . It may be 2 , 4 or some other number next time, But it should return only values .How to do it ?
Upvotes: 0
Views: 1880
Reputation: 1972
The essence of the answer is to loop through the list, and for each dictionary, extract the value(s) you want and stick it in a new list.
Assuming each dictionary only has a single entry with key "S"
, as in your example, you could do it in one line:
l = [d["S"] for d in category]
In the more general case, if we assume nothing about the number of entries in each dictionary, the single-line solution becomes only slightly more unwieldy
l = [value for d in category for value in d.values()]
Personally, I find the multi-line solution a little easier to follow:
l = []
for d in category:
for value in d.values():
l.append(value)
Upvotes: 2
Reputation:
Give this a try
category = [ { "S" : "Restaurants" }, { "S" : "Drinks" }, { "S" : "Outdoor Seating" }]
for data,cat in enumerate(category):
for value,key in cat.items():
category[data]=key
print(category)
Upvotes: 1
Reputation: 5889
I suggest using list comprehension to iterate through the list and get all the values of each dict.
category = [ { "S" : "Restaurants" }, { "S" : "Drinks" }, { "S" : "Outdoor Seating" }]
new = [list(dicx.values())[0] for dicx in category]
output
['Restaurants', 'Drinks', 'Outdoor Seating']
Upvotes: 1