简体   繁体   中英

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) ?

Then, when I get my_list I can achive proper output using script like this:

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? 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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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