嘟嘟社区

python 的 list 怎么匹配 json 啊


genre_movie = ‘{"genres":[{"id":28,"name":"动作"},{"id":12,"name":"冒险"},{"id":16,"name":"动画"},{"id":35,"name":"喜剧"},{"id":80,"name":"犯罪"},{"id":99,"name":"纪录"},{"id":18,"name":"剧情"},{"id":10751,"name":"家庭"},{"id":14,"name":"奇幻"},{"id":36,"name":"历史"},{"id":27,"name":"恐怖"},{"id":10402,"name":"音乐"},{"id":9648,"name":"悬疑"},{"id":10749,"name":"爱情"},{"id":878,"name":"科幻"},{"id":10770,"name":"电视电影"},{"id":53,"name":"惊悚"},{"id":10752,"name":"战争"},{"id":37,"name":"西部"}]}’

genre_ids = [80, 9648, 53]

想匹配生成  genre_ids = [犯罪, 悬疑, 惊悚]

应该怎么写啊

本帖最后由 falomsc 于 2022-3-29 17:11 编辑

import json
import pandas as pd

genre_movie = ‘{"genres":[{"id":28,"name":"动作"},{"id":12,"name":"冒险"},{"id":16,"name":"动画"},{"id":35,"name":"喜剧"},{"id":80,"name":"犯罪"},{"id":99,"name":"纪录"},{"id":18,"name":"剧情"},{"id":10751,"name":"家庭"},{"id":14,"name":"奇幻"},{"id":36,"name":"历史"},{"id":27,"name":"恐怖"},{"id":10402,"name":"音乐"},{"id":9648,"name":"悬疑"},{"id":10749,"name":"爱情"},{"id":878,"name":"科幻"},{"id":10770,"name":"电视电影"},{"id":53,"name":"惊悚"},{"id":10752,"name":"战争"},{"id":37,"name":"西部"}]}’
df = pd.DataFrame(json.loads(genre_movie).get(‘genres’))

def get_genre_ids(genre_ids_in: list) -> list:
    genre_ids_out = [df[df.id == i].iat[0, 1] for i in genre_ids_in]
    return genre_ids_out

key/value反转呗
遍历呗
先用json生成字典
正则提取出来。
本帖最后由 NP_Prob 于 2022-3-29 16:50 编辑

json genre_movie到dict,然后在key "genres"下是一个list,这个list里面每个又是一个dict,每个dict有两个key,一个是"id",一个是"name",你可以用"id"做key,用"name"做value,再弄个新的dict,new_dict = {"28": "动作", …, "37": "西部"},最后genre_ids = [80, 9648, 53],就可以有genre_name = [new_dict[genre_ids[0]], new_dict[genre_ids[1]]…],当然最后一步你可以写个函数处理了。

falomsc 发表于 2022-3-29 16:59
import json
import pandas as pd

这个是不是整复杂了。。。

本帖最后由 NP_Prob 于 2022-3-29 17:45 编辑

falomsc 发表于 2022-3-29 16:59
import json
import pandas as pd

受这个启发,最后把dataframe转成dict就可以了。
前面还是一样:

  1. df = pd.DataFrame(json.loads(genre_movie).get(‘genres’))

复制代码

然后:

  1. dict_new = dict(zip(df[‘id’],df[‘name’]))

复制代码

或者可以这样:

  1. dict_new = df.set_index(‘id’).to_dict()[‘name’]

复制代码

开始没想到pandas