简体   繁体   中英

how to create a dictionary with list of dictionaries as values from a list of dictionaries

I have this sample list of dictionaries:

[
  {
    "name": "like father", 
    "director": "Ajun kun", 
    "edited": "2014-12-20T21:23:49.867000Z", 
    "similar_movies": [
      "http://movies.dev/api/films/1/", 
      "http://movies.dev/api/films/3/", 
   
    ], 
    "rating": "2.0", 

  }, 
  {
    "name": "be like her", 
    "director": tuned ku", 
    "edited": "2014-12-20T21:23:49.870000Z", 
    "similar_movies": [
      "http://movies.dev/api/films/1/"
    ]
  }, .......
]

Some of the dictionaries in the list contain ratings while others do not. I want to generate a new dictionary of like the dictionary below sorted by the ratings:

    {
        "movies":[
            {"name": "movie_4", "rating" : 0.1},
            {"name": "movie_1", "rating" : 0.3},
            {"name": "movies_5", "rating" : 0.5}
        ],
        "movies_without_rating": [
            {"name": "movie_8"},
            {"name": "movie_3"} 
        ]
    }

Here is my sample code:

from flask import Flask,  jsonify, request
import requests
from collections import ChainMap

app = Flask(__name__)

@app.route('/movies', methods=['GET'])
def returnAll():
     #note: the URL is just a demo url
    response = requests.get("https://movies.dev/api/movies/")

    results = response.json()['results']

    general_dic = {}


  
    for result in result:
        for key, val in result:
            if (key == 'rating'):
                general_dic['movies'] 
             else:
                 general_dic['movies_with_rating']
    
    return general_dic

    
    return jsonify(results)





if __name__ == "__main__":
    app.run(debug=True)

I got stuck and I couldn't continue, I will greatly appreciate your help.

It seems something like this is what you'd like:

def separate_movies(movies_list):
    movies_with_rating = []
    movies_without_rating = []
    
    for movie in movies_list:
        name = movie["movies"]
        if "rating" in movie:
            movies_with_rating.append({
                "name": name,
                "rating": movie["rating"]
            })
        else:
            movies_without_rating.append({
                "name": name
            })
    
    movies_with_rating.sort(key = lambda movie: movie["rating"])

    return {
        "movies": movies_with_rating,
        "movies_without_rating": movies_without_rating
    }

The key here is using the in keyword to check whether a movie has a rating.

You can use this example to integrate in your code:

lst = [
  {
    "movies": "like father", 
    "rating": "2.0", 
  }, 
  {
    "movies": "other  movie", 
    "rating": "2.5", 
  }, 
  {
    "movies": "be like her", 
  }, 
  {
    "movies": "other  movie 2", 
    "rating": "5.5", 
  }, 
  {
    "movies": "other  movie 3", 
  }, 
]

out = {'movies':[], 'movies_without_rating':[]}
for movie in lst:
    if 'rating' in movie:
        out['movies'].append({'name': movie['movies'], 'rating': float(movie['rating'])})
    else:
        out['movies_without_rating'].append({'name': movie['movies']})

# sort it
out['movies'] = sorted(out['movies'], key=lambda k: k['rating'])


# pretty print on screen:
from pprint import pprint
pprint(out)

Prints:

{'movies': [{'name': 'like father', 'rating': 2.0},
            {'name': 'other  movie', 'rating': 2.5},
            {'name': 'other  movie 2', 'rating': 5.5}],
 'movies_without_rating': [{'name': 'be like her'}, {'name': 'other  movie 3'}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM