Finglish
Finglish

Reputation: 9956

Check if python dictionary contains value and if so return related value

I have a list of dicts, which contain filenames and modification dates in the following format:

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

I need to query if a fileName exists in the dictionary and if so return the fileMod value for that entry.

Upvotes: 4

Views: 7076

Answers (5)

juliomalegria
juliomalegria

Reputation: 24921

You can solve this problem nicely using a generator and the next method:

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

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

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

Upvotes: 2

Phil Cooper
Phil Cooper

Reputation: 5877

Right, you've updated your question to indicate a list of dicts as Janne pointed out. But now your statement is not true that:

I am checking if the fileName exists using if filename in filelist: statement, which is working correctly

Ricardo got it right, you need a dict of modTimes or a dict of dicts. Easily created from your fileList 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>)

Upvotes: 2

Abhijit
Abhijit

Reputation: 63717

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"]

Upvotes: 3

Pablo
Pablo

Reputation: 8644

Using a list comprehension:

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

Upvotes: 6

Constantinius
Constantinius

Reputation: 35039

Just for the record: your data structure is a list of dictionaries, not a dictionary. So you cannot simply query the list for the item "fileName". You could do it like this:

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

Upvotes: 3

Related Questions