gpt4 book ai didi

python - 如何在Python中的字典元素列表中访问字典?

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

我有一个字典,其值是字典列表。例如 -

dj={'101': [{'Name': 'vamc'}, {'House': 'yes'}, {'married': 'yes'}, {'car': '1'}], '102': [{'Name': 'suresh'}, {'House': 'no'}, {'married': 'yes'}, {'car': '0'}]}

我想访问 id = '102' 的汽车属性。我尝试了这样的方法来解决我的问题。

li=[]
dj={}

def indec():
di1={}
di2={}
di3={}
di4={}
di1['Name']=input("Enter the Name")
di2['House']=input("Enter the House status")
di3['married']=input("Enter the married status")
di4['car']=input("Enter no of cars")
li=[di1,di2,di3,di4]
return li


x=int(input("Enter How many values:"))
for i in range(x):
y=input("Enter id")
dj[y]=indec()

id=input("Enter the id whose no of cars do u want:")
print("No of cars are:",dj[id['car']])

任何更简单的解决方案将不胜感激。

最佳答案

@MaximGi 提到的面向对象方法

#Class to encapsulate person
class Person:

def __init__(self, id, name, house, married, car):
self.id = id
self.name = name
self.house = house
self.married = married
self.car = car


li=[]

#Get input values from user
def indec():

name=input("Enter the Name")
house=input("Enter the House status")
married=input("Enter the married status")
car=input("Enter no of cars")
return name, house, married, car

#In a for loop, create a person object and append it to list
x=int(input("Enter How many values:"))
for i in range(x):
y=input("Enter id")
p = Person(y, *indec())
li.append(p)


id=input("Enter the id whose no of cars do u want:")
#Loop through person list and print car attribute for which the id matches
for p in li:
if p.id == id:
print("No of cars are:",p.car)

输出结果为

Enter How many values:2
Enter id101
Enter the Namevamc
Enter the House statusyes
Enter the married statusyes
Enter no of cars1
Enter id102
Enter the Namesuresh
Enter the House statusyes
Enter the married statusno
Enter no of cars0
Enter the id whose no of cars do u want:102
No of cars are: 0

关于python - 如何在Python中的字典元素列表中访问字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55497699/

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