skip to Main Content

I am currently building a Telegram Bot and getting JSON response on Google Places API to return nearby locations to users.
The json Response I get is as follows:


results" : [
      {
         "name" : "Golden Village Tiong Bahru",
         "opening_hours" : {
            "open_now" : true
         },
         "rating" : 4.2,
         "types" : [ "movie_theater", "point_of_interest", "establishment" ],
         "user_ratings_total" : 773
      },
      {
         "name" : "Cathay Cineplex Cineleisure Orchard",
         "opening_hours" : {
            "open_now" : true
         },
         "rating" : 4.2,
         "types" : [ "movie_theater", "point_of_interest", "establishment" ],
         "user_ratings_total" : 574
      }
]


My current code to get specific items in the dictionary

json.dumps([[s['name'], s['rating']] for s in object_json['results']], indent=3)

Current Results:

[
   [
      "Golden Village Tiong Bahru",
      4.2
   ],
   [
      "Cathay Cineplex Cineleisure Orchard",
      4.2
   ]
]

I would like to get the name and rating and display side by side instead:

Golden Village Tiong Bahru : 4.2, 
Cathay Cineplex Cineleisure Orchard : 4.2

Please help.

2

Answers


  1. Maybe with:

    json.dumps([s['name'] + ": " + str(s['rating']) for s in object_json['results']], indent=3)
    
    Login or Signup to reply.
  2. Do you want json format as a result?
    Then you can do:

    json.dumps({
        s['name']: s['rating']
        for s in object_json['results']
    }, indent=3)
    

    If you want just string list:

    lines = [f"{s['name']}: {s['rating']}" for s in object_json['results']]
    

    Or you want to print only:

    for s in object_json['results']:
        print(f"{s['name']}: {s['rating']}")
    

    You need 3.6 or higher python interpreter to use f-string(f"...").

    I you don’t, replace
    f"{s['name']}: {s['rating']}" -> '{name}: {rating}'.format(**s)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search