我们会使用字典来存储,例如:
a={"breakfast":"banana","lunch":"fish","dinner":"soup"}
如果您想在每个键值集旁添加时间属性,您的方法是什么?当然不是:
a={"8AM":"breakfast":"banana","2PM":"lunch":"fish","8PM":"dinner":"soup"}
然后我想使用一个或多个键来访问一个值。
也许通过列表诀窍?
答案 0 :(得分:5)
您可以使用元组作为字典键:
a = {("8AM", "breakfast"): "banana",
("2PM", "lunch"): "fish",
("8PM", "dinner"): "soup",
}
答案 1 :(得分:5)
使用带有元组的字典作为键:
>>> a={("8AM","breakfast"):"banana",("2PM","lunch"):"fish",("8PM","dinner"):"soup"}
>>> a["8AM","breakfast"]
'banana'
或者如果你想只用餐名来查看时间和食物:
>>> a={"breakfast":("8AM","banana"),"lunch":("2PM","fish"),"dinner":("8PM","soup")}
>>> a["breakfast"]
('8AM', 'banana')
答案 2 :(得分:2)
由于你想使用字典和可能的列表,我建议你确定你的"主键"是和创建一个这样的嵌套结构:
a = {
'breakfast': {
'time': "8AM",
'items': ['banana', 'yogurt']
},
'lunch': {
'time': '2PM',
'items': ['fish', 'tartar sauce']
},
'dinner': {
'time': '8PM',
'items': ['soup', 'salad']
}
}
每顿饭的时间各不相同,但我们都知道我们吃早餐,午餐和晚餐(或者至少我们应该吃)。这样,您就可以确定消耗的时间和项目:
a['breakfast']['time']
'8AM'
a['breakfast']['items']
['banana', 'yogurt']
答案 3 :(得分:1)
a = {"8AM":{"breakfast":"banana"},"2PM":{"lunch":"fish"},"8PM":{"dinner":"soup"}}
使用:
>>>a['8AM']['breakfast']
'banana'
其他:
def r(_d,_target):
result = []
for k, v in _d.items():
if(k == _target):
if type(v) == type({}):
for x in v.keys():
result.append(v[x])
else:
result.append(v)
if type(v) == type({}):
r2 = r(v,_target)
if len(r2) > 0:
for l in r2:
result.append(l)
return result
>>> r(a,"breakfast")
['banana']
>>> r(a,"8AM")
['banana']
>>> r(a,"dinner")
['soup']