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

Time:05-23

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.

CodePudding user response:

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

CodePudding user response:

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()))
  • Related