1

我们将使用字典来存储例如:

a={"breakfast":"banana","lunch":"fish","dinner":"soup"}

如果您想在每个键值集旁边添加时间属性,您的方法是什么。当然不是:

a={"8AM":"breakfast":"banana","2PM":"lunch":"fish","8PM":"dinner":"soup"}

然后我想使用一个或多个键来访问一个值。

也许通过使用列表做一个技巧?

4

4 回答 4

5

您可以使用元组作为字典键:

a = {("8AM", "breakfast"): "banana",
     ("2PM", "lunch"): "fish",
     ("8PM", "dinner"): "soup",
    }
于 2013-03-22T23:42:19.923 回答
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')
于 2013-03-22T23:42:32.400 回答
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']
于 2013-03-22T23:47:51.227 回答
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']
于 2013-03-22T23:53:30.090 回答