Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge directories values or separate strings in python?

I’m fetching data from JSON API and key values from the array but with the for loop, it’s fetching them separately and can’t manage to merge it to show an output like,

Example: Action, Adventure, Fantasy, Science Fiction (I want to display the key values separately with ‘,’)

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import requests
import json

API = 'API_HERE'
URL = 'https://api.themoviedb.org/3/movie/19995?api_key=' + API + '&language=en-US'
response = requests.get(URL)
data = response.json()

for g in data['genres']:
    #gen = g['name']
    print(g)

This is the output I’m getting

{'id': 28, 'name': 'Action'}
{'id': 12, 'name': 'Adventure'}       
{'id': 14, 'name': 'Fantasy'}         
{'id': 878, 'name': 'Science Fiction'}

This is how the JSON output looks like

enter image description here

I know this is the simple task but can’t manage to figure out or accomplish it.

If I loop through the values it just displays values differently.

for g in data['genres']:
    gen = g['name']
    print(type(gen))

enter image description here

>Solution :

I think you are looking for .join() which you can use like this

names = [d["name"] for d in data["genres"]]
print(", ".join(names))

EDIT based on your comment:

If you want to use a for loop instead, you have to create a list and append the name of every genre to that list:

names = []
for g in data["genres"]:
    names.append(g["name"])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading