简体   繁体   English

如何使用字典列表作为字典列表中的值创建字典

[英]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.这里的关键是使用in关键字来检查电影是否有评级。

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'}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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