gpt4 book ai didi

python - 按值获取 python 字典中的项目位置

转载 作者:太空宇宙 更新时间:2023-11-03 20:36:03 26 4
gpt4 key购买 nike

我有一个Python字典,其中有嵌套的键和值。如何通过提供值来查找对象的索引号。

目前,当我知道对象的索引时,我可以获取特定对象中键的值。

我的意思是,如果我知道该对象在字典中的索引号,我就可以获取该特定对象中的键和值。

my_dict = {
"ftml": {
"people": {
"person": [
{
"@id": "Terach",
"@sex": "male",
"Death": {
"@year": ""
},
"Midrash": {
"@midrah": ""
},
"Old": {
"@age": ""
},
"Role": {
"@role": ""
},
"birth": {
"@year": ""
},
"father": {
"@id": "Nachor"
},
"mother": {
"@id": ""
},
"spouse": ""
},
{
"@id": "Avraham",
"@sex": "male",
"Death": {
"@year": "2123"
},
"Grandson": {
"@son1": "Esav",
"@son2": "Yaakov"
},
"Midrash": {
"@midrah": ""
},
"Old": {
"@age": "175"
},
"Role": {
"@role": ""
},
"birth": {
"@year": "1948"
},
"father": {
"@id": "Terach"
},
"mother": {
"@id": ""
},
"spouse": {
"@wife1": "Sara"
}
},
{
"@husband": "Avraham",
"@id": "Sara",
"@sex": "female"
},
{
"@id": "Nachor",
"@sex": "male",
"Death": {
"@year": ""
},
"Midrash": {
"@midrah": ""
},
"Old": {
"@age": ""
},
"Role": {
"@role": ""
},
"birth": {
"@year": ""
},
"father": {
"@id": "Terach"
},
"mother": {
"@id": ""
},
"spouse": ""
},
]
}
}
}



x = int(input("Type the chronological person number. (i.e 1 is Avraham): "))

print("First Name: ",my_dict['ftml']['people']['person'][x]["@id"]) #1 = avraham

我希望向用户询问 @id 并返回对象的索引号。

例如,如果用户发送程序“Avraham”,程序将返回 1。

如果用户正在寻找 Nachor,程序将返回 0。

最佳答案

我认为修改字典不是一个好主意。这是我的解决方案:

首先获取列表的“位置”,即从中查找内容。

list_to_find = my_dict['ftml']['people']['person']

list_to_find 是一个字典(人)列表,例如

[{"@id": "Terach", '@sex': ...}, {"@id": 'Avraham', ...} ...]

那么你要做的就是搜索所有@id,这样你就可以通过以下方式获取所有@id:

ids = [person['@id'] for person in list_to_find]

然后使用index获取索引:

index = ids.index('Avraham')

关于python - 按值获取 python 字典中的项目位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57167572/

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