0

I am a little stuck with the following task that I am trying to sort out as I am just learning Python. I need to sort out "city" from the json file that looks like:

[{
    "city": "Las Vegas",
    "operator": "",
    "browser_name": "chromium",
    "browser_version": "55",
    "country_code": "us",
    "country": "United States",
    "location_code": "2e4efc13-6a6a-45ba-a6aa-ec4eb1f4fb2b|north-america.na.us.west.lasvegas|chromium|55",
    "location_tier": "1"
}, {
    "city": "Las Vegas",
    "operator": "",
    "browser_name": "firefox",
    "browser_version": "46",
    "country_code": "us",
    "country": "United States",
    "location_code": "2e4efc13-6a6a-45ba-a6aa-ec4eb1f4fb2b|north-america.na.us.west.lasvegas|firefox|46",
    "location_tier": "1"
}, ...

I have the code like this:

import json, operator

file_path = './response.json'

with open(file_path) as f:
    data = json.loads(f.read())
    print(data[0]['city'])

The thing is that I need comma separated output to a console like "city, city, city...". Would appreciate any help! Thanks a lot!

0

2 Answers 2

1
print(', '.join(item['city'] for item in data))

Also, have a look at this answer, using inflect package that will allow for properly constructed list in English, e.g. city, city, and city

Sign up to request clarification or add additional context in comments.

Comments

0

You are very close to the result. You can have a list like this. Code;

import json, operator
file_path = './response.json'
result = []
with open(file_path) as f:
    data = json.loads(f.read())
    for d in data:
        result.append(d['city'])
print(result)

Output; ['Las Vegas', 'Las Vegas']

2 Comments

@Zendem, why import operator?
I didn't want to change your friend's code. I guess he will use it later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.