是否可以在python中访问dict的第n个元素

时间:2018-03-07 16:52:53

标签: python dictionary

我有一段代码片段,函数foo返回一个字典。

def foo():
    # do something here
    # get data from web
    return {
        "book": {ln : wd for ln, wd, _ in data["book"]},
        "note": {ln : wd for ln, wd, _ in data["note"]},
    }

def bar():
    data = foo()
    # how to access 0th element of data["book"]
    # data["book"][0] doesnt work

问题是如何访问其第一个元素?

1 个答案:

答案 0 :(得分:3)

list(data.items())将为您提供字典中所有条目的列表版本,作为(key, value)形式的元组,您可以根据需要迭代或索引:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> print(list(d.items())[0])
('a', 1)

所以在你的情况下,list(data['books'].items())