Search code examples
pythondictionarysetdictionary-comprehension

Unique values of Dictionary comprehension, return dictionary instread of string


this is my data:

data = [{'id': 1, 'name': 'The Musical Hop', 'city': 'San Francisco', 'state': 'CA'},
{'id': 2, 'name': 'The Dueling Pianos Bar', 'city': 'New York', 'state': 'NY'},
{'id': 3, 'name': 'Park Square Live Music & Coffee', 'city': 'San Francisco', 'state': 'CA'}]

I want to find out the unique values (thats why I use a set) of "city" and return them like this:

cities = set([x.get("city") for x in data])
cities ´

{'New York', 'San Francisco'}

However, I also want to return the corresponding state, like this:

[{"city": "New York", "state": "NY"}, {"city":  "San Francisco", "state": "CA"}]

Is there a way to do this?


Solution

  • You can use dict-comprehension for the task:

    out = list({x['city']:{'city':x['city'], 'state':x['state']} for x in data}.values())
    
    print(out)
    

    Prints:

    [{'city': 'San Francisco', 'state': 'CA'}, {'city': 'New York', 'state': 'NY'}]