Den Contre
Den Contre

Reputation: 245

Filter list of dictionaries

This is my example:

dictlist = [{'first': 'James', 'last': 'Joule'}, 
            {'first': 'James','last': 'Watt'},
            {'first': 'Christian','last': 'Doppler'}]

I am trying to get the last name. If this was in a model, the code would be:

getdata = Name.objects.filter(name="Christian")
getLastName = getdata.last

and I would get "Doppler".

Upvotes: 9

Views: 31878

Answers (7)

Hope this is helpful to you!!

"; my_dict=[
{
    'username':"Siva",
    'phoneno':"12345678915",
    'city':"Chennai"
},
{
    'username':"Sundhar",
    'phoneno':"12345678917",
    'city':"Vellore"
},
    {
    'username':"cockroach",
    'phoneno':"12345668919",
    'city':"Chennai"
},
    {
        'username':"oggy",
        'phoneno':"12345678917",
        'city':"Chennai"
    }
]

";phoneno="12345678917"

result = [user['username'] for user in my_dict if user['phoneno']== phoneno]

Upvotes: -3

PatDuJour
PatDuJour

Reputation: 975

To start with, we can have a simple script that just uses the built-in python filter method, and this might already be sufficient:

fl = list(filter(lambda x: x['first'] == 'Christian', dictlist))

# you can't use `.property` because this is a dictionary, not a object
fl[0]['last']
# returns Doppler

I realize your example is a Django code, so if you want to make this more dynamic so that you are able to filter by any key in the dictionary:

def dict_filter(dictlist: list, key: str, value: str) -> list:
    return list(filter(lambda x: x.get(key) == value, dictlist))

dict_filter(dictlist, 'first', 'Christian')
# similar to django's filter method returns a queryset, this returns a list:
# [{'first': 'Christian', 'last': 'Doppler'}]

dict_filter(dictlist, 'last', 'Doppler')
# returns [{'first': 'Christian', 'last': 'Doppler'}]

dict_filter(dictlist, 'last', 'notfound')
# returns []

And an example to use python filter method to create a similar function to Django's QuerySet.get method:

def dict_get(dictlist: list, key: str, value: str) -> list:
    ret = list(filter(lambda x: x.get(key) == value, dictlist))
    if len(ret) == 0:
        raise Exception('Not Found')
    if len(ret) > 1:
        raise Exception(f'Found more than 1 object with {key}={value}')
    return ret[0]

dict_get(dictlist, 'first', 'Christian')
# returns {'first': 'Christian', 'last': 'Doppler'}
    
dict_get(dictlist, 'first', 'Christians')
# raises Exception: Not Found

dict_get(dictlist, 'first', 'James')
# raises Exception: Found more than 1 object with first=James

Hope this is helpful to you!

Upvotes: 4

Kurt Bourbaki
Kurt Bourbaki

Reputation: 12626

I sometimes like to use next:

next((d['last'] for d in dictlist if d['first'] == 'Christian'), None)
# 'Doppler'

The first argument is an iterator and the second (optional) argument is the default value returned if no matching entry is found.

Note: this will only return the first matching result. So it wouldn't be good if you expect to have multiple records matching your "query".

Upvotes: 2

liaofeng
liaofeng

Reputation: 82

for comp in dictlist:
    if comp["first"] == 'Christian':
        return comp["last"]

Upvotes: -4

Sdwdaw
Sdwdaw

Reputation: 1037

This is very simple solution with list comprehension:

>>> dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
>>> [x['last'] for x in dictlist if x['first'] == 'Christian']
['Doppler']

Upvotes: 21

chucksmash
chucksmash

Reputation: 6017

dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
the_jameses = [d for d in dictlist if d['first'] == 'James']

Where the resulting list contains only:

[{'first': 'James', 'last': 'Joule'}, {'first': 'James', 'last': 'Watt'}]

Upvotes: 10

Tim
Tim

Reputation: 43394

Something like this should work

last_name = ''

for d in dictList:
  if d['first'] == 'Christian':
    last_name = d['last']
    break

Upvotes: 3

Related Questions