简体   繁体   中英

How to extract list of specific keys from the dictionary in Python?

I have a list of dictionaries that looks like that:

lst = [{'id': 'ID1', 'Name':'Name1', 'Surname':'Surname1'},
       {'id': 'ID2', 'Name':'Name2', 'Surname':'Surname2'},
       {'id': 'ID3', 'Name':'Name3', 'Surname':'Surname3'}]

I would like my output to look like that:

idnumber: ID1 ; Name: Name1 ; Surname: Surname1
idnumber: ID2 ; Name: Name2 ; Surname: Surname2
idnumber: ID3 ; Name: Name3 ; Surname: Surname3

As my strarting point, at least to start with id part, I wrote:

for l in lst:
    for key,value in l.items():
        if l.keys() == "id":
            print("idnumber: ", l.values())

Unfortunately, it doesn't work for me :( Any suggestion would be helpful.

Here is an approach:

lst = [{'id': 'ID1', 'Name':'Name1', 'Surname':'Surname1'},
       {'id': 'ID2', 'Name':'Name2', 'Surname':'Surname2'},
       {'id': 'ID3', 'Name':'Name3', 'Surname':'Surname3'}]


keys = ['id', 'Name', 'Surname']
aliases = {'id': 'idnumber'}
for d in lst:
    for i, k in enumerate(keys):
        print(f'{aliases.get(k, k)}: {d[k]}',
              end=' ; ' if i+1<len(keys) else '\n')

output:

idnumber: ID1 ; Name: Name1 ; Surname: Surname1
idnumber: ID2 ; Name: Name2 ; Surname: Surname2
idnumber: ID3 ; Name: Name3 ; Surname: Surname3

How it works:

  • keys holds the list of keys to use in order
  • aliases holds the name of the key to print ( aliases.get(k, k) searches for an alias and uses the key name if there is no alias)
  • enumerate allows to identify the last key to print a newline instead of the ; separator

Iterate over the list of dictionaries and format each key-value pairs to finally join them together.

lst = [{'id': 'ID1', 'Name':'Name1', 'Surname':'Surname1'},
       {'id': 'ID2', 'Name':'Name2', 'Surname':'Surname2'},
       {'id': 'ID3', 'Name':'Name3', 'Surname':'Surname3'}]

for d in lst:
    print('; '.join(f"{k}: {v}" for k, v in d.items()))

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