Check if the python dictionary contains a value, and if so, return the corresponding value

I have a dicts list that contains file names and modification dates in the following format:

fileList = [{"fileName": "file1.txt", "fileMod": "0000048723"}, {"fileName": "file2.txt", "fileMod": "0000098573"}] 

I need to query if fileName in the dictionary, and if so, return the fileMod value for this entry.

+4
source share
5 answers

Using list comprehension:

 fileMod = [item['fileMod'] for item in fileList if item['fileName'] == filename] 
+6
source

You can use lambda with filter .

 >>> fileList = [{"fileName": "filename1.typ", "fileMod": "0000000001"}, {"fileName": "filename2.typ", "fileMod": "0000000002"}] >>> filter(lambda x:x["fileName"]=="filename2.typ",fileList)[0]['fileMod'] '0000000002' 

You can also do this using List-Comprehension

 [x['fileMod'] for x in fileList if x["fileName"]=="filename2.typ"][0] 

Or just a simple iteration

 for x in fileList: if x["fileName"]=="filename2.typ": print x["fileMod"] 
+3
source

For the record only: your data structure is a list of dictionaries, not a dictionary. Therefore, you cannot just query the list for the "fileName" element. You can do it as follows:

 for filedict in fileList: if filedict.get("fileName") == "myrequestedfile.typ": # to somthing pass 
+3
source

That's right, you updated your question by listing dicts, as Janne pointed out. But now your statement is wrong:

I check if fileName exists using if filename in the listlist: statement file which works correctly

Ricardo got it right, you need a modTimes diploma or a dicts recorder. Easily created from your file with:
 fileList = dict((f['fileName'],f) for f in fileList) mod = fileList.get('file1.txt',<default>) # or fileList = dict((f['fileName'],f) for f in fileList) mod = fileList.get('file1.txt',{}).get('fileMod',<default>) 
+2
source

You can solve this problem with generator and next :

 next(x['fileMod'] for x in fileList if x['fileName'] == 'my filename') 

Of course, this causes a StopIteration error if the generator is empty (there was no dict in your list with fileName == 'my filename' ). You can avoid the error caused by:

 try: next(x['fileMod'] for x in fileList if x['fileName']=='my filename') except StopIteration: print 'Oops! file not found' 
+2
source

Source: https://habr.com/ru/post/1388834/


All Articles