gpt4 book ai didi

python - 如何从Python中的字典列表中获取所有一个键?

转载 作者:行者123 更新时间:2023-12-01 04:37:16 25 4
gpt4 key购买 nike

我有一个很大的 JSON 文件,如下所示:

{
"data" : [
{"album": "I Look to You", "writer": "Leon Russell", "artist": "Whitney Houston", "year": "2009", "title": "\"A Song for You\""},
{"album": "Michael Zager Band", "writer": "Michael Zager", "artist": "Whitney Houston", "year": "1983", "title": "\"Life's a Party\""},
{"album": "Paul Jabara & Friends", "writer": "Paul Jabara", "artist": "Whitney Houston", "year": "1978", "title": "\"Eternal Love\""},
...

...我正在尝试制作一个非常简单的 API 来获取不同的值。现在,我可以相当轻松地获取 localhost/data/1/title 例如,获取第一个标题值,但我想通过执行 来获取所有 标题>localhost/titles 之类的。我如何修改此处的 do_GET 方法来添加此类功能?

def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()

path = self.path[1:]
components = string.split(path, '/')

node = content
for component in components:
if len(component) == 0 or component == "favicon.ico":
continue

if type(node) == dict:
node = node[component]

elif type(node) == list:
node = node[int(component)]

self.wfile.write(json.dumps(node))

return

最佳答案

这里的答案将遵循您当前的动态 URL 模式,无需重大架构更改或要求。

在这里,我使用“all”代替您的网址模式中给定的数字索引,因为我觉得这更好地代表了您的data/[item(s)]/[attribute]范例

以下是一些 URL 和示例输出:

  1. /data/1/album =>“迈克尔·扎格乐队”
  2. /data/0/title => “一首给你的歌”
  3. /data/all/title => [“为你献上一首歌”、“生活就是一场派对”、“永恒的爱”]
  4. /data/all/year => ["2009", "1983", "1978"]
  5. /data/1 => {"album": "Michael Zager Band", "title": "Life's a Party", "writer": "Michael Zager", "year": “1983”,“艺术家”:“惠特尼·休斯顿”}

PS - 我稍微改变了架构,使用递归,我认为这更好地遵循你想要做的事情。

def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()

path = self.path[1:]
components = string.split(path, '/')

node = parse_node(content, components)

self.wfile.write(json.dumps(node))

return

def parse_node(node, components):
# For a valid node and component list:
if node and len(components) and components[0] != "favicon.ico":
# Dicts will return parse_node of the top-level node component found,
# reducing the component list by 1
if type(node) == dict:
return parse_node(node.get(components[0], None), components[1:])

elif type(node) == list:
# A list with an "all" argument will return a full list of sub-nodes matching the rest of the URL criteria
if components[0] == "all":
return [parse_node(n, components[1:]) for n in node]
# A normal list node request will work as it did previously
else:
return parse_node(node[int(components[0])], components[1:])
else:
return node

# Handle bad URL
return None

关于python - 如何从Python中的字典列表中获取所有一个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31508846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com