Home > other >  How do i iterate through a list having dictionaries in it,ietration must be done on the values of on
How do i iterate through a list having dictionaries in it,ietration must be done on the values of on

Time:06-10

I want to go through all 'filenames' keys to read it. For example i want to read '20220214T132301560.jpg' like this all jpg files in it. how shall i do that?

list=[{'convertedDate': '2022-02-14 13:23:01.560000',
  'filename': '20220214T132301560.jpg'},
 {'convertedDate': '2022-02-14 13:23:03.840000',
  'filename': '20220214T132303840.jpg'},
 {'convertedDate': '2022-02-14 13:23:07.860000',
  'filename': '20220214T132307860.jpg'}]

CodePudding user response:

If you are trying to access all of the filename values:

_list = [
    {'convertedDate': '2022-02-14 13:23:01.560000', 'filename': '20220214T132301560.jpg'},
    {'convertedDate': '2022-02-14 13:23:03.840000', 'filename': '20220214T132303840.jpg'},
    {'convertedDate': '2022-02-14 13:23:07.860000', 'filename': '20220214T132307860.jpg'}
]

jpegs = [d['filename'] for d in _list]
print(jpegs)
['20220214T132303840.jpg', '20220214T132303840.jpg', '20220214T132307860.jpg']

CodePudding user response:

This will return the dict entry in your list if it's filename matches your desired value:

def foo(target):
    _list=[{'convertedDate': '2022-02-14 13:23:01.560000',
      'filename': '20220214T132301560.jpg'},
     {'convertedDate': '2022-02-14 13:23:03.840000',
      'filename': '20220214T132303840.jpg'},
     {'convertedDate': '2022-02-14 13:23:07.860000',
      'filename': '20220214T132307860.jpg'}]

    for d in _list:
        for k, v in d.items():
            if v == target:
                return d

print(foo("20220214T132301560.jpg"))

RESULT: {'convertedDate': '2022-02-14 13:23:01.560000', 'filename': '20220214T132301560.jpg'}

Notes: Do not use list as a variable name. It is a type name, reserved in Python.

  • Related