将元组中的变量信息添加到嵌套字典中

问题描述 投票:0回答:1

我有几个包含带有视频信息序列的元组的列表,例如:

[(1, "n_videos", 3), (2, "video_id", "top.001"), (3, "video_author", "mary louise"), (4, "video_topic", "ecology"), (5, "video_id", "top.002"), (6, "video_author", "john meyer"), (7, "video_topic", "anatomy"), (7, "video_id", "top.003"), (8, "video_author", "mary louise"), (9, "video_topic", "ethics")]

我需要将它们转换成这样的字典:

"video_metadata": {
  "n_videos": 3,
  "top.001": {
     "video_topic": "ecology",
     "video_author": "mary louise"},
  "top.002": {
     "video_topic": "anatomy",
     "video_author": "john meyer"
  }, ...
}

我已经尝试过这个,但我没有得到正确的嵌套:

for triple in archive:
    if triple[1] == "video_id":
        triple[1] = dict()
        triple[1].update({triple[1], triple[2]})

您将如何以最有效的方式解决这个问题?

python dictionary tuples
1个回答
0
投票
archive = [(1, "n_videos", 3), (2, "video_id", "top.001"), (3, "video_author", 
"mary louise"),(4, "video_topic", "ecology"), (5, "video_id", "top.002"), (6, 
"video_author", "john meyer"), (7, "video_topic", "anatomy"), (8, "video_id", 
"top.003"), (9, "video_author", "mary louise"),(10, "video_topic", "ethics")]

video_metadata = {"video_metadata": {}}
current_video_id = None

for triple in archive:
if triple[1] == "n_videos":
    video_metadata["video_metadata"]["n_videos"] = triple[2]
elif triple[1] == "video_id":
    current_video_id = triple[2]
    video_metadata["video_metadata"][current_video_id] = {}
  else:
    video_metadata["video_metadata"][current_video_id][triple[1]] = triple[2]

 print(video_metadata)
  • 此代码初始化一个空字典(video_metadata)并迭代元组列表。

  • 它检查元组的第二个元素是否是“n_videos”或“video_id”以处理特殊情况。对于“n_videos”,它直接更新外部字典。

  • 对于“video_id”,它设置 current_video_id 变量并为该 video_id 初始化一个空字典。然后使用 current_video_id 作为键将后续元组添加到嵌套字典中。

© www.soinside.com 2019 - 2024. All rights reserved.