gpt4 book ai didi

python - 无法超越 JSON 文件中的第一个字典

转载 作者:行者123 更新时间:2023-12-01 07:59:54 25 4
gpt4 key购买 nike

我正在尝试迭代 JSON 文件来搜索特定部分并打印出文件的该部分。但我的代码仅适用于文件中的第一个字典,任何过去的内容都会让我的代码打印出 JSON 文件的部分不存在。这是 JSON 文件:

[
{
"Name": "Debian",
"Version": "9",
"Install": "apt",
"Owner": "SPI",
"Kernel": "4.9"
},
{
"Name": "Ubuntu",
"Version": "17.10",
"Install": "apt",
"Owner": "Canonical",
"Kernel": "4.13"
},
{
"Name": "Fedora",
"Version": "26",
"Install": "dnf",
"Owner": "Red Hat",
"Kernel": "4.13"
},
{
"Name": "CentOS",
"Version": "7",
"Install": "yum",
"Owner": "Red Hat",
"Kernel": "3.10"
},
{
"Name": "OpenSUSE",
"Version": "42.3",
"Install": "zypper",
"Owner": "Novell",
"Kernel": "4.4"
},
{
"Name": "Arch Linux",
"Version": "Rolling Release",
"Install": "pacman",
"Owner": "SPI",
"Kernel": "4.13"
},
{
"Name": "Gentoo",
"Version": "Rolling Release",
"Install": "emerge",
"Owner": "Gentoo Foundation",
"Kernel": "4.12"
}

]

这是我的代码:

import json

jsonfile = raw_input("Choose a json file: ")
type(jsonfile)

name = input("Type in the name: ")
type(name)

with open (jsonfile) as myfile:
data = myfile.read()

obj = json.loads(data)

for i in obj:
if i["Name"] == name:
print(i["Version"])
break
else:
print("Title not found")
break

假设我输入名称“Debian”,我就可以得到版本号。但是,如果我输入“Fedora”,我会得到代码的“标题未找到”部分。这意味着该名称不在 JSON 文件中,但它确实存在。任何帮助,将不胜感激。

最佳答案

为了简单起见:

s = [
{
"Name": "Debian",
"Version": "9",
"Install": "apt",
"Owner": "SPI",
"Kernel": "4.9"
},
{
"Name": "Ubuntu",
"Version": "17.10",
"Install": "apt",
"Owner": "Canonical",
"Kernel": "4.13"
},
{
"Name": "Fedora",
"Version": "26",
"Install": "dnf",
"Owner": "Red Hat",
"Kernel": "4.13"
},
{
"Name": "CentOS",
"Version": "7",
"Install": "yum",
"Owner": "Red Hat",
"Kernel": "3.10"
},
{
"Name": "OpenSUSE",
"Version": "42.3",
"Install": "zypper",
"Owner": "Novell",
"Kernel": "4.4"
},
{
"Name": "Arch Linux",
"Version": "Rolling Release",
"Install": "pacman",
"Owner": "SPI",
"Kernel": "4.13"
},
{
"Name": "Gentoo",
"Version": "Rolling Release",
"Install": "emerge",
"Owner": "Gentoo Foundation",
"Kernel": "4.12"
}
]

使用列表理解:

search = 'Fedora'

print([x['Version'] for x in s if x['Name'] == search])

输出:

['26']

说明:

search = 'Fedora'

for elem in s: # for each elem in the list
if elem['Name'] == search: # check if the Name is what you're looking for
print(elem['Version']) # print the Version if it is

输出:

26

关于python - 无法超越 JSON 文件中的第一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55777640/

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