简体   繁体   English

如何获取存储在Python字典中的列表?

[英]How to get list stored in Python dictionary?

I have a dictionary where every key has multiple values assigned as a list.我有一个字典,其中每个键都有多个分配为列表的值。

Output looks like this:输出如下所示:

>>> print(db_state)
defaultdict(<class 'list'>, {'787777': ['firstdb', 'online', 'seconddb', 'enabled', 'thirtdb', 'terminated'], '332123': ['forthdb', 'terminated', 'fifthdb', 'online'], '85756': ['sixthdb', 'online'], '85787673': ['seventhdb', 'enabled', 'eighthdb', 'terminated'] ...

Code that gives mentioned output:给出上述输出的代码:

db_state = defaultdict(list)
for d in data['dblist']['dbparameters']:
    db_details = u['db_code']
    db_nr = u['id']
    status = u['state']
    db_state[db_nr].append(db_nr)
    db_state[db_nr].append(status)

I would like to extract the list when key ( db_details ) is equal to variable db_id (from different part of script, not visible here) ?当键( db_details )等于变量db_id (来自脚本的不同部分,此处不可见)时,我想提取列表?

Then, when I get my_list I can achive proper output using script like this:然后,当我得到my_list 时,我可以使用这样的脚本获得正确的输出:

my_list = db_state.get(db_id)
if my_list is not None:
    print(f"This is list of db_nr and states for {db_id}:")
    for db_nr, status in my_list:
        print(f"{db_nr} is {status}")
else:
    print(f"No data for {db_id}!!")

To sum up how should I extract only list part (I called my_list for now) from db_state dictionary?总结一下,我应该如何从db_state字典中只提取列表部分(我现在称为my_list )? I am not sure if indexing would be a good idea here.我不确定在这里建立索引是否是个好主意。 Maybe there is some other, simplier way for that?也许还有其他更简单的方法?

dict = {"Letters": list}
print(dict)

Just have list defined and add the name as the value 只需定义列表,然后将名称添加为值

Looks like you need list slicing with step argument and zip . 看起来您需要使用step参数和zip列表切片。

Ex: 例如:

my_list = db_state.get(db_id)
if my_list is not None:
    print(f"This is list of db_nr and states for {db_id}:")
    for db_nr, status in zip(my_list[::2], my_list[1::2]):
        print(f"{db_nr} is {status}")
else:
    print(f"No data for {db_id}!!") 

Output: 输出:

firstdb is online
seconddb is enabled
thirtdb is terminated
>>> db_id='787777'
>>> dict(filter(lambda x:x[0]==db_id,db_state.items())).values()
dict_values([['firstdb', 'online', 'seconddb', 'enabled', 'thirtdb', 'terminated']])

If you want the lists for the value that matches your db then you can use this, but since keys are unique in a dictionary why cant you just do db_state.get(db_id,None) and if it is None it means there is no entry for that db_id . 如果您想要列出与您的数据库匹配的值的列表,则可以使用它,但是由于键在字典中是唯一的,为什么不能执行db_state.get(db_id,None) ;如果它是None则表示没有条目对于该db_id

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

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