Home > Back-end >  How to merge directories values or separate strings in python?
How to merge directories values or separate strings in python?

Time:10-02

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:

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

CodePudding user response:

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"])
  • Related