[Tutor] Accessing Specific Dictionary items

Steven D'Aprano steve at pearwood.info
Tue Aug 2 00:37:59 CEST 2011


Mike Nickey wrote:
> The input being used is through pygeoip.
> Using this I am pulling the data by IP and from what I am reading this
> populates as a dictionary.
> 
> Here is some of the output that I can show currently
> [{'city': 'Buena Park', 'region_name': 'CA', 'area_code': 714},
> {'city': 'Wallingford', 'region_name': 'CT', 'area_code': 203},
> {'city': 'Schenectady', 'region_name': 'NY', 'area_code': 518},
> {'city': 'Athens', 'region_name': '35'}]
> 
> I'd like to have an output similar to this:
> 'Buena Park', 'Wallingford', 'Schenectady','Athens' pulled by the
> "city" keys that are used in the returns. 


What do you mean, "the returns"?

If all you want is a list of cities, that's easy:

cities = [d['city'] for d in list_of_dicts]


or if you prefer a more verbose way:

cities = []
for d in list_of_dicts:
     cities.append(d['city'])


To get the list sorted, just sort it afterwards:

cities.sort()


> I think the easiest way to
> approach this would be simply to use the .append and populate a list
> but I don't know how to pull an item by key value from the dictionary
> returns.

The same way you would pull an item by key from any other dict.




-- 
Steven



More information about the Tutor mailing list