简体   繁体   English

在词典列表中找到一个项目

[英]find an item inside a list of dictionaries

Say I have a list of dictionaries. 说我有一个词典列表。 each dict in the list has 3 elements. 列表中的每个字典都有3个元素。 Name, id and status. 姓名,身份和身份。

list_of_dicts = [{'id':1, 'name':'Alice', 'status':0},{'id':2, 'name':'Bob', 'status':0},{'id':3, 'name':'Robert', 'status':1}]

so I get: 所以我得到:

In[20]: print list_of_dicts
Out[20]: 
[{'id': 1, 'name': 'Alice', 'status': 0},
 {'id': 2, 'name': 'Bob', 'status': 0},
 {'id': 3, 'name': 'Robert', 'status': 1}]

If i recieve a name, how can I get its status without iterating on the list? 如果我收到一个名字,如何在不重复列表的情况下获得其状态?
eg I get 'Robert' and I want to output 1. 例如,我得到'罗伯特',我想输出1。
thank you. 谢谢。

for example you can use pandas 例如,你可以使用熊猫

import pandas as pd
list_of_dicts = [{'id':1, 'name':'Alice', 'status':0},{'id':2, 'name':'Bob', 'status':0},{'id':3, 'name':'Robert', 'status':1}]

a = pd.DataFrame(list_of_dicts)
a.loc[a['name'] == 'Robert']

and play with dataframes its very fast because write on c++ and easy (like sql queries) 并且使用数据帧非常快,因为在c ++上编写并且很容易(比如sql查询)

I don't think you can do what you ask without iterating through the dictionary: 我不认为你可以做你所要求的,而不必遍历字典:
Best case, you'll find someone that suggests you a method that hides the iteration. 最好的情况是,你会发现有人建议你隐藏迭代的方法。

If what really concerns you is the speed, you may break your iteration as soon as you find the first valid result: 如果您真正关心的是速度,您可能会在找到第一个有效结果后立即中断迭代:

for iteration, elements in enumerate(list_of_dicts):
    if elements['name'] == "Robert":
        print "Elements id: ", elements['id']
        break
print "Iterations: ", iteration

# OUTPUT: Elements id: 3, Iterations: 1

Note that numbers of iteration may vary, since dictionaries are not indexed, and if you have more "Roberts" , only for one the "id" will be printed 请注意,迭代次数可能会有所不同,因为字典未编入索引,如果您有更多"Roberts" ,则仅打印一个"id"将被打印

It's not possible to do this without iteration. 没有迭代就不可能做到这一点。

However, but you can transform you dictionary into a different data structure, such as a dictionary where names are the keys: 但是,您可以将字典转换为不同的数据结构,例如名称为键的字典:

new_dict = {person["name"]: {k: v for k, v in person.items() if k != "name"} for person in list_of_dicts}

Then you can get the status like so: 然后你就可以得到这样的状态:

new_dict["Robert"]["status"]
# 1

Additionally, as @tobias_k mentions in the comments, you can keep the internal dictionary the same: 另外,正如@tobias_k在评论中提到的那样,您可以保持内部字典相同:

{person["name"]: person for person in list_of_dicts}

The only issue with the above approaches is that it can't handle multiple names. 上述方法的唯一问题是它无法处理多个名称。 You can instead add the unique id into the key to differentiate between names: 您可以将唯一ID添加到键中以区分名称:

new_dict = {(person["name"], person["id"]): person["status"] for person in list_of_dicts}

Which can be called like this: 可以这样调用:

new_dict["Robert", 3]
# 1

Even though it takes extra computation(only once) to create these data structures, the lookups afterwards will be O(1), instead of iterating the list every time when you want to search a name. 即使创建这些数据结构需要额外的计算(仅一次),之后的查找将是O(1),而不是每次要搜索名称时迭代列表。

As you found you have to iterate (unless you are able to change your data structure to an enclosing dict) why don't you just do it? 正如您发现必须迭代(除非您能够将数据结构更改为封闭的字典),为什么不这样做呢?

>>> [d['status'] for d in list_of_dicts if d['name']=='Robert']
[1]

Despite this, I recommend considering a map type (like dict) every time you see some 'id' field in a proposed data structure. 尽管如此,我建议每次在建议的数据结构中看到一些'id'字段时考虑地图类型(如dict)。 If it's there you probably want to use it for general identification, instead of carrying dicts around. 如果它在那里你可能想用它进行一般识别,而不是携带dicts。 They can be used for relations also, and transfer easily into a relational database if you need it later. 它们也可用于关系,如果以后需要,可以轻松转移到关系数据库中。

Your list_of_dicts cannot be reached without a loop so for your desire your list should be modified a little like 1 dict and many lists in it: 没有循环就无法访问你的list_of_dicts所以为了你的愿望你的列表应该被修改一点像一个dict和其中的许多列表

list_of_dicts_modified = {'name':['Alice', 'Bob', 'Robert'],'id':[1, 2, 3], 'status': [0, 0, 1]}
index = list_of_dicts_modified['name'].index(input().strip())
print('Name: {0} ID: {1} Status: {2}'.format(list_of_dicts_modified['name'][index], list_of_dicts_modified['id'][index], list_of_dicts_modified['status'][index]))

Output: 输出:

C:\Users\Documents>py test.py
Alice
Name: Alice ID: 1 Status: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM