Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字典列表中获取所有键_Python_List_Dictionary - Fatal编程技术网

Python 从字典列表中获取所有键

Python 从字典列表中获取所有键,python,list,dictionary,Python,List,Dictionary,如果我有一本包含列表的词典,如下所示: {"items": [{"name": "Orange", "cost": 5}, {"name": "Apple", "cost": 10}]} 是否有可能以某种方式从两个列表中获取键“name”和“cost”? 这只是因为我不想在每次向同一列表中的字典添加新内容时再添加一行。我假设,通过获取键,您指的是与这些键关联的值 a['items']是一个列表。只需遍历它并访问名称和成本值,就像访问任何字典一样 >>> a_dict = {"

如果我有一本包含列表的词典,如下所示:

{"items": [{"name": "Orange", "cost": 5}, {"name": "Apple", "cost": 10}]}
是否有可能以某种方式从两个列表中获取键“name”和“cost”?
这只是因为我不想在每次向同一列表中的字典添加新内容时再添加一行。

我假设,通过获取键,您指的是与这些键关联的值

a['items']
是一个列表。只需遍历它并访问
名称
成本
值,就像访问任何字典一样

>>> a_dict = {"items": [{"name": "Orange", "cost": 5}, {"name": "Apple", "cost": 10}]}
>>> for a_d in a_dict['items']:
        print 'Name: {} Cost: {}'.format(a_d['name'], a_d['cost'])
d = {"fruit": [{"name": "Orange", "cost": 5}, {"name": "Apple", "cost": 10}],
    "vegetables": [{"name": "carrot", "cost": 5}, {"name": "eggplant", "cost": 10}]}

for group, items in d.items():
    for item in items:
        print item['name']  

>>>
carrot
eggplant
Orange
Apple
这使得:

Name: Orange Cost: 5
Name: Apple Cost: 10
['cost', 'name']
['cost', 'name']
如果实际上您需要列表
a['items']
中词典的键名,可以使用
.keys()
获取它们:

这使得:

Name: Orange Cost: 5
Name: Apple Cost: 10
['cost', 'name']
['cost', 'name']

避免代码重复的最佳方法是使用函数

def get_name_and_cost(d):
    return d['name'], d['cost']

for d in lst['items']:
    name, cost = get_name_and_cost(d)
    print(name, cost)
def get_values(d, *keys):
    t = []
    for k in keys:
        if k in d.keys():
            t.append(d[k])
        else:
            t.append(None)
    return t

如果你有一组以上的“条目”,这将贯穿字典中的每一组

>>> a_dict = {"items": [{"name": "Orange", "cost": 5}, {"name": "Apple", "cost": 10}]}
>>> for a_d in a_dict['items']:
        print 'Name: {} Cost: {}'.format(a_d['name'], a_d['cost'])
d = {"fruit": [{"name": "Orange", "cost": 5}, {"name": "Apple", "cost": 10}],
    "vegetables": [{"name": "carrot", "cost": 5}, {"name": "eggplant", "cost": 10}]}

for group, items in d.items():
    for item in items:
        print item['name']  

>>>
carrot
eggplant
Orange
Apple

我认为一种更动态、可重用的方法是创建一个函数

def get_name_and_cost(d):
    return d['name'], d['cost']

for d in lst['items']:
    name, cost = get_name_and_cost(d)
    print(name, cost)
def get_values(d, *keys):
    t = []
    for k in keys:
        if k in d.keys():
            t.append(d[k])
        else:
            t.append(None)
    return t

然后你可以做这样的事情

>>> d = {"items": [{"name": "Orange", "cost": 5}, {"name": "Apple", "cost": 10}]}
>>> for item in d["items"]:
...     print "Name {}, Cost {}".format(*get_values(item, "name", "cost"))
...
Name Orange, Cost 5
Name Apple, Cost 10

你能给我们举一个你想要达到的目标的例子吗?也许给我们您目前拥有的代码,我们可以提供进一步的指导您想要什么样的数据表示?我认为清单中的字典正是你想要的。你的目的不清楚。我想从列表中的字典中提取“名称”和“成本”,但我已经得到了一个不错的答案:但是我没有得到-1。这里没有特别的代码,我想用它做一些事情。我认为我的解释足够了,我解释说我想从列表中的两个词典中获取“name”和“cost”的值,因为我不想每次都添加一行新词来分别获取它们。