Python как найти в списке словарь

You can use a generator expression:

>>> dicts = [
...     { "name": "Tom", "age": 10 },
...     { "name": "Mark", "age": 5 },
...     { "name": "Pam", "age": 7 },
...     { "name": "Dick", "age": 12 }
... ]

>>> next(item for item in dicts if item["name"] == "Pam")
{'age': 7, 'name': 'Pam'}

If you need to handle the item not being there, then you can do what user Matt suggested in his comment and provide a default using a slightly different API:

next((item for item in dicts if item["name"] == "Pam"), None)

And to find the index of the item, rather than the item itself, you can enumerate() the list:

next((i for i, item in enumerate(dicts) if item["name"] == "Pam"), None)

Mike 'Pomax' Kamermans's user avatar

answered Dec 28, 2011 at 8:31

Frédéric Hamidi's user avatar

Frédéric HamidiFrédéric Hamidi

257k41 gold badges484 silver badges478 bronze badges

11

This looks to me the most pythonic way:

people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]

filter(lambda person: person['name'] == 'Pam', people)

result (returned as a list in Python 2):

[{'age': 7, 'name': 'Pam'}]

Note: In Python 3, a filter object is returned. So the python3 solution would be:

list(filter(lambda person: person['name'] == 'Pam', people))

David Schumann's user avatar

answered Aug 18, 2014 at 22:46

PaoloC's user avatar

PaoloCPaoloC

3,4112 gold badges15 silver badges18 bronze badges

8

@Frédéric Hamidi’s answer is great. In Python 3.x the syntax for .next() changed slightly. Thus a slight modification:

>>> dicts = [
     { "name": "Tom", "age": 10 },
     { "name": "Mark", "age": 5 },
     { "name": "Pam", "age": 7 },
     { "name": "Dick", "age": 12 }
 ]
>>> next(item for item in dicts if item["name"] == "Pam")
{'age': 7, 'name': 'Pam'}

As mentioned in the comments by @Matt, you can add a default value as such:

>>> next((item for item in dicts if item["name"] == "Pam"), False)
{'name': 'Pam', 'age': 7}
>>> next((item for item in dicts if item["name"] == "Sam"), False)
False
>>>

fragilewindows's user avatar

answered Aug 13, 2015 at 12:48

Mike N's user avatar

Mike NMike N

6,1954 gold badges23 silver badges21 bronze badges

1

You can use a list comprehension:

def search(name, people):
    return [element for element in people if element['name'] == name]

answered Dec 28, 2011 at 8:32

5

I tested various methods to go through a list of dictionaries and return the dictionaries where key x has a certain value.

Results:

  • Speed: list comprehension > generator expression >> normal list iteration >>> filter.
  • All scale linear with the number of dicts in the list (10x list size -> 10x time).
  • The keys per dictionary does not affect speed significantly for large amounts (thousands) of keys. Please see this graph I calculated: https://imgur.com/a/quQzv (method names see below).

All tests done with Python 3.6.4, W7x64.

from random import randint
from timeit import timeit


list_dicts = []
for _ in range(1000):     # number of dicts in the list
    dict_tmp = {}
    for i in range(10):   # number of keys for each dict
        dict_tmp[f"key{i}"] = randint(0,50)
    list_dicts.append( dict_tmp )



def a():
    # normal iteration over all elements
    for dict_ in list_dicts:
        if dict_["key3"] == 20:
            pass

def b():
    # use 'generator'
    for dict_ in (x for x in list_dicts if x["key3"] == 20):
        pass

def c():
    # use 'list'
    for dict_ in [x for x in list_dicts if x["key3"] == 20]:
        pass

def d():
    # use 'filter'
    for dict_ in filter(lambda x: x['key3'] == 20, list_dicts):
        pass

Results:

1.7303 # normal list iteration 
1.3849 # generator expression 
1.3158 # list comprehension 
7.7848 # filter

answered Feb 24, 2018 at 0:51

user136036's user avatar

user136036user136036

10.9k6 gold badges45 silver badges46 bronze badges

3

people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]

def search(name):
    for p in people:
        if p['name'] == name:
            return p

search("Pam")

Ricky Robinson's user avatar

answered Dec 28, 2011 at 8:30

satoru's user avatar

satorusatoru

31.4k31 gold badges90 silver badges140 bronze badges

2

Have you ever tried out the pandas package? It’s perfect for this kind of search task and optimized too.

import pandas as pd

listOfDicts = [
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]

# Create a data frame, keys are used as column headers.
# Dict items with the same key are entered into the same respective column.
df = pd.DataFrame(listOfDicts)

# The pandas dataframe allows you to pick out specific values like so:

df2 = df[ (df['name'] == 'Pam') & (df['age'] == 7) ]

# Alternate syntax, same thing

df2 = df[ (df.name == 'Pam') & (df.age == 7) ]

I’ve added a little bit of benchmarking below to illustrate pandas’ faster runtimes on a larger scale i.e. 100k+ entries:

setup_large = 'dicts = [];
[dicts.extend(({ "name": "Tom", "age": 10 },{ "name": "Mark", "age": 5 },
{ "name": "Pam", "age": 7 },{ "name": "Dick", "age": 12 })) for _ in range(25000)];
from operator import itemgetter;import pandas as pd;
df = pd.DataFrame(dicts);'

setup_small = 'dicts = [];
dicts.extend(({ "name": "Tom", "age": 10 },{ "name": "Mark", "age": 5 },
{ "name": "Pam", "age": 7 },{ "name": "Dick", "age": 12 }));
from operator import itemgetter;import pandas as pd;
df = pd.DataFrame(dicts);'

method1 = '[item for item in dicts if item["name"] == "Pam"]'
method2 = 'df[df["name"] == "Pam"]'

import timeit
t = timeit.Timer(method1, setup_small)
print('Small Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_small)
print('Small Method Pandas: ' + str(t.timeit(100)))

t = timeit.Timer(method1, setup_large)
print('Large Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_large)
print('Large Method Pandas: ' + str(t.timeit(100)))

#Small Method LC: 0.000191926956177
#Small Method Pandas: 0.044392824173
#Large Method LC: 1.98827004433
#Large Method Pandas: 0.324505090714

answered Sep 1, 2016 at 21:12

abby sobh's user avatar

abby sobhabby sobh

1,57419 silver badges15 bronze badges

1

To add just a tiny bit to @FrédéricHamidi.

In case you are not sure a key is in the the list of dicts, something like this would help:

next((item for item in dicts if item.get("name") and item["name"] == "Pam"), None)

answered Dec 9, 2015 at 23:18

Drazen Urch's user avatar

Drazen UrchDrazen Urch

2,7511 gold badge21 silver badges23 bronze badges

1

You can achieve this with the usage of filter and next methods in Python.

filter method filters the given sequence and returns an iterator.
next method accepts an iterator and returns the next element in the list.

So you can find the element by,

my_dict = [
    {"name": "Tom", "age": 10},
    {"name": "Mark", "age": 5},
    {"name": "Pam", "age": 7}
]

next(filter(lambda obj: obj.get('name') == 'Pam', my_dict), None)

and the output is,

{'name': 'Pam', 'age': 7}

Note: The above code will return None incase if the name we are searching is not found.

answered Dec 17, 2019 at 6:08

Manoj Kumar S's user avatar

1

One simple way using list comprehensions is , if l is the list

l = [
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]

then

[d['age'] for d in l if d['name']=='Tom']

answered Jan 30, 2020 at 10:45

chink's user avatar

chinkchink

1,4672 gold badges27 silver badges65 bronze badges

def dsearch(lod, **kw):
    return filter(lambda i: all((i[k] == v for (k, v) in kw.items())), lod)

lod=[{'a':33, 'b':'test2', 'c':'a.ing333'},
     {'a':22, 'b':'ihaha', 'c':'fbgval'},
     {'a':33, 'b':'TEst1', 'c':'s.ing123'},
     {'a':22, 'b':'ihaha', 'c':'dfdvbfjkv'}]



list(dsearch(lod, a=22))

[{'a': 22, 'b': 'ihaha', 'c': 'fbgval'},
 {'a': 22, 'b': 'ihaha', 'c': 'dfdvbfjkv'}]



list(dsearch(lod, a=22, b='ihaha'))

[{'a': 22, 'b': 'ihaha', 'c': 'fbgval'},
 {'a': 22, 'b': 'ihaha', 'c': 'dfdvbfjkv'}]


list(dsearch(lod, a=22, c='fbgval'))

[{'a': 22, 'b': 'ihaha', 'c': 'fbgval'}]

answered Sep 20, 2020 at 23:48

internety's user avatar

internetyinternety

3643 silver badges10 bronze badges

Simply using list comprehension:

[i for i in dct if i['name'] == 'Pam'][0]

Sample code:

dct = [
    {'name': 'Tom', 'age': 10},
    {'name': 'Mark', 'age': 5},
    {'name': 'Pam', 'age': 7}
]

print([i for i in dct if i['name'] == 'Pam'][0])

> {'age': 7, 'name': 'Pam'}

answered Aug 13, 2018 at 14:08

Teoretic's user avatar

TeoreticTeoretic

2,4351 gold badge18 silver badges28 bronze badges

2

This is a general way of searching a value in a list of dictionaries:

def search_dictionaries(key, value, list_of_dictionaries):
    return [element for element in list_of_dictionaries if element[key] == value]

answered Jul 19, 2014 at 21:36

ipegasus's user avatar

ipegasusipegasus

14.7k9 gold badges52 silver badges73 bronze badges

dicts=[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]

from collections import defaultdict
dicts_by_name=defaultdict(list)
for d in dicts:
    dicts_by_name[d['name']]=d

print dicts_by_name['Tom']

#output
#>>>
#{'age': 10, 'name': 'Tom'}

answered Dec 28, 2011 at 9:15

Rusty Rob's user avatar

Rusty RobRusty Rob

16.3k8 gold badges97 silver badges115 bronze badges

names = [{'name':'Tom', 'age': 10}, {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}]
resultlist = [d    for d in names     if d.get('name', '') == 'Pam']
first_result = resultlist[0]

This is one way…

answered Dec 28, 2011 at 8:34

Niclas Nilsson's user avatar

Niclas NilssonNiclas Nilsson

5,6413 gold badges30 silver badges43 bronze badges

1

You can try this:

''' lst: list of dictionaries '''
lst = [{"name": "Tom", "age": 10}, {"name": "Mark", "age": 5}, {"name": "Pam", "age": 7}]

search = raw_input("What name: ") #Input name that needs to be searched (say 'Pam')

print [ lst[i] for i in range(len(lst)) if(lst[i]["name"]==search) ][0] #Output
>>> {'age': 7, 'name': 'Pam'} 

answered Dec 3, 2018 at 4:41

Siddharth Satpathy's user avatar

Put the accepted answer in a function to easy re-use

def get_item(collection, key, target):
    return next((item for item in collection if item[key] == target), None)

Or also as a lambda

   get_item_lambda = lambda collection, key, target : next((item for item in collection if item[key] == target), None)

Result

    key = "name"
    target = "Pam"
    print(get_item(target_list, key, target))
    print(get_item_lambda(target_list, key, target))

    #{'name': 'Pam', 'age': 7}
    #{'name': 'Pam', 'age': 7}

In case the key may not be in the target dictionary use dict.get and avoid KeyError

def get_item(collection, key, target):
    return next((item for item in collection if item.get(key, None) == target), None)

get_item_lambda = lambda collection, key, target : next((item for item in collection if item.get(key, None) == target), None)

answered Nov 17, 2021 at 6:15

Federico Baù's user avatar

Federico BaùFederico Baù

5,5555 gold badges27 silver badges36 bronze badges

Most (if not all) implementations proposed here have two flaws:

  • They assume only one key to be passed for searching, while it may be interesting to have more for complex dict
  • They assume all keys passed for searching exist in the dicts, hence they don’t deal correctly with KeyError occuring when it is not.

An updated proposition:

def find_first_in_list(objects, **kwargs):
    return next((obj for obj in objects if
                 len(set(obj.keys()).intersection(kwargs.keys())) > 0 and
                 all([obj[k] == v for k, v in kwargs.items() if k in obj.keys()])),
                None)

Maybe not the most pythonic, but at least a bit more failsafe.

Usage:

>>> obj1 = find_first_in_list(list_of_dict, name='Pam', age=7)
>>> obj2 = find_first_in_list(list_of_dict, name='Pam', age=27)
>>> obj3 = find_first_in_list(list_of_dict, name='Pam', address='nowhere')
>>> 
>>> print(obj1, obj2, obj3)
{"name": "Pam", "age": 7}, None, {"name": "Pam", "age": 7}

The gist.

answered Apr 29, 2020 at 7:35

onekiloparsec's user avatar

My first thought would be that you might want to consider creating a dictionary of these dictionaries … if, for example, you were going to be searching it more a than small number of times.

However that might be a premature optimization. What would be wrong with:

def get_records(key, store=dict()):
    '''Return a list of all records containing name==key from our store
    '''
    assert key is not None
    return [d for d in store if d['name']==key]

answered Dec 28, 2011 at 8:32

Jim Dennis's user avatar

Jim DennisJim Dennis

17k12 gold badges66 silver badges115 bronze badges

2

Here is a comparison using iterating throuhg list, using filter+lambda or refactoring(if needed or valid to your case) your code to dict of dicts rather than list of dicts

import time

# Build list of dicts
list_of_dicts = list()
for i in range(100000):
    list_of_dicts.append({'id': i, 'name': 'Tom'})

# Build dict of dicts
dict_of_dicts = dict()
for i in range(100000):
    dict_of_dicts[i] = {'name': 'Tom'}


# Find the one with ID of 99

# 1. iterate through the list
lod_ts = time.time()
for elem in list_of_dicts:
    if elem['id'] == 99999:
        break
lod_tf = time.time()
lod_td = lod_tf - lod_ts

# 2. Use filter
f_ts = time.time()
x = filter(lambda k: k['id'] == 99999, list_of_dicts)
f_tf = time.time()
f_td = f_tf- f_ts

# 3. find it in dict of dicts
dod_ts = time.time()
x = dict_of_dicts[99999]
dod_tf = time.time()
dod_td = dod_tf - dod_ts


print 'List of Dictionries took: %s' % lod_td
print 'Using filter took: %s' % f_td
print 'Dict of Dicts took: %s' % dod_td

And the output is this:

List of Dictionries took: 0.0099310874939
Using filter took: 0.0121960639954
Dict of Dicts took: 4.05311584473e-06

Conclusion:
Clearly having a dictionary of dicts is the most efficient way to be able to search in those cases, where you know say you will be searching by id’s only.
interestingly using filter is the slowest solution.

answered Jan 16, 2016 at 13:01

Kőhalmy Zoltán's user avatar

I would create a dict of dicts like so:

names = ["Tom", "Mark", "Pam"]
ages = [10, 5, 7]
my_d = {}

for i, j in zip(names, ages):
    my_d[i] = {"name": i, "age": j}

or, using exactly the same info as in the posted question:

info_list = [{"name": "Tom", "age": 10}, {"name": "Mark", "age": 5}, {"name": "Pam", "age": 7}]
my_d = {}

for d in info_list:
    my_d[d["name"]] = d

Then you could do my_d["Pam"] and get {"name": "Pam", "age": 7}

answered Jan 29, 2021 at 11:46

Mike's user avatar

MikeMike

6681 gold badge9 silver badges15 bronze badges

Ducks will be a lot faster than a list comprehension or filter. It builds an index on your objects so lookups don’t need to scan every item.

pip install ducks

from ducks import Dex

dicts = [
  {"name": "Tom", "age": 10},
  {"name": "Mark", "age": 5},
  {"name": "Pam", "age": 7}
]

# Build the index
dex = Dex(dicts, {'name': str, 'age': int})

# Find matching objects
dex[{'name': 'Pam', 'age': 7}]

Result: [{'name': 'Pam', 'age': 7}]

answered Jun 22, 2022 at 20:29

manimino's user avatar

maniminomanimino

1,2451 gold badge11 silver badges11 bronze badges

You have to go through all elements of the list. There is not a shortcut!

Unless somewhere else you keep a dictionary of the names pointing to the items of the list, but then you have to take care of the consequences of popping an element from your list.

answered Dec 28, 2011 at 8:44

jimifiki's user avatar

jimifikijimifiki

5,3442 gold badges34 silver badges58 bronze badges

3

I found this thread when I was searching for an answer to the same
question. While I realize that it’s a late answer, I thought I’d
contribute it in case it’s useful to anyone else:

def find_dict_in_list(dicts, default=None, **kwargs):
    """Find first matching :obj:`dict` in :obj:`list`.

    :param list dicts: List of dictionaries.
    :param dict default: Optional. Default dictionary to return.
        Defaults to `None`.
    :param **kwargs: `key=value` pairs to match in :obj:`dict`.

    :returns: First matching :obj:`dict` from `dicts`.
    :rtype: dict

    """

    rval = default
    for d in dicts:
        is_found = False

        # Search for keys in dict.
        for k, v in kwargs.items():
            if d.get(k, None) == v:
                is_found = True

            else:
                is_found = False
                break

        if is_found:
            rval = d
            break

    return rval


if __name__ == '__main__':
    # Tests
    dicts = []
    keys = 'spam eggs shrubbery knight'.split()

    start = 0
    for _ in range(4):
        dct = {k: v for k, v in zip(keys, range(start, start+4))}
        dicts.append(dct)
        start += 4

    # Find each dict based on 'spam' key only.  
    for x in range(len(dicts)):
        spam = x*4
        assert find_dict_in_list(dicts, spam=spam) == dicts[x]

    # Find each dict based on 'spam' and 'shrubbery' keys.
    for x in range(len(dicts)):
        spam = x*4
        assert find_dict_in_list(dicts, spam=spam, shrubbery=spam+2) == dicts[x]

    # Search for one correct key, one incorrect key:
    for x in range(len(dicts)):
        spam = x*4
        assert find_dict_in_list(dicts, spam=spam, shrubbery=spam+1) is None

    # Search for non-existent dict.
    for x in range(len(dicts)):
        spam = x+100
        assert find_dict_in_list(dicts, spam=spam) is None

answered Jan 18, 2018 at 15:12

Deacon's user avatar

DeaconDeacon

3,5652 gold badges30 silver badges52 bronze badges

Short and multi words search:

selected_items=[item for item in items if item['name'] in ['Mark','Pam']]

answered May 12 at 13:35

Solivan's user avatar

SolivanSolivan

6751 gold badge8 silver badges16 bronze badges

The problem of getting only the suitable dictionary that has a particular value of the corresponding key is quite common when one starts working with a dictionary in Python. Let’s discuss certain ways in which this task can be performed.

Method 1: Get a list of values from a List of Dictionary using a loop 

This is the brute force method by which this task can be performed. For this, we just use naive check and compare and return the result once we find the suitable match and break for the rest of the dictionaries. 

Python3

test_list = [

    {'Course': "C++", 'Author': "Jerry"},

    {'Course': "Python", 'Author': "Mark"},

    {'Course': "Java", 'Author': "Paul"}]

res = None

for sub in test_list:

    if sub['Author'] == "Mark":

        res = sub

        break

print("The filtered dictionary value is : " + str(res))

Output :

The filtered dictionary value is : {'Course': 'Python', 'Author': 'Mark'}

Time Complexity: O(n)
Auxiliary Space: O(1)

Method 2: Get a list of values from a List of Dictionary using next() + dictionary comprehension 

The combination of these methods can also be used to perform this task. This difference is that it’s a one-liner and more efficient as the next function uses an iterator as an internal implementation which is quicker than generic methods. 

Python3

test_list = [

    {'Course': "C++", 'Author': "Jerry"},

    {'Course': "Python", 'Author': "Mark"},

    {'Course': "Java", 'Author': "Paul"}]

res = next((sub for sub in test_list if sub['Course'] == "Java"), None)

print("The filtered dictionary value is : " + str(res))

Output:

The filtered dictionary value is : {'Course': 'Java', 'Author': 'Paul'}

Method 3: Get a list of values from a List of Dictionary using a list comprehension

In this method, we are simply using a function and passing the name we want to search and the test_list and with the help of list comprehension, we return the list.

Python3

test_list = [

    {'Course': "C++", 'Author': "Jerry"},

    {'Course': "Python", 'Author': "Mark"},

    {'Course': "Java", 'Author': "Paul"}]

def search(name, test_list):

    return [element for element in test_list if element['Author'] == name]

res = search("Paul", test_list)

print(res)

Output:

[{'Course': 'Java', 'Author': 'Paul'}]

Method 4: Get a list of values from a List of Dictionary using a filter method

In this method, we are filtering our required result using the Python filter method, and then implicating it into a Python list(). 

Python3

test_list = [

    {'Course': "C++", 'Author': "Jerry"},

    {'Course': "Python", 'Author': "Mark"},

    {'Course': "Java", 'Author': "Paul"}]

res = list(filter(lambda test_list: test_list['Author'] == 'Jerry', test_list))

print(res)

Output:

[{'Course': 'C++', 'Author': 'Jerry'}]

Method 5: Using the list.index() method

  1. Create a list of the ‘Course’ values in the dictionaries in the list using a list comprehension.
  2. Use the index() method to find the index of the target value in the list of ‘Course’ values.
  3. Use the index to return the matching dictionary from the original list.
  4. If no match is found, return None.

Python3

test_list = [

    {'Course': "C++", 'Author': "Jerry"},

    {'Course': "Python", 'Author': "Mark"},

    {'Course': "Java", 'Author': "Paul"}]

target_value = "Java"

course_list = [d['Course'] for d in test_list]

try:

    index = course_list.index(target_value)

except ValueError:

    index = None

if index is not None:

    res = test_list[index]

else:

    res = None

print("The filtered dictionary value is : " + str(res))

Output

The filtered dictionary value is : {'Course': 'Java', 'Author': 'Paul'}

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n), where n is the length of the input list. 

METHOD 6:Using defaultdict method.

APPROACH:

This code uses collections.defaultdict to create a dictionary of lists, where the keys are the values of the “Course” key and the values are lists of dictionaries that have that value. It then gets the list of dictionaries that have “Python” as the value for “Course” and returns the first one.

ALGORITHM:

1.Import the collections.defaultdict method.
2.Create a list of dictionaries test_list.
3.Create an empty defaultdict called course_dict.
4.Iterate through the test_list and append each dictionary to the list that corresponds to the value of the “Course” key in course_dict.
5.Get the list of dictionaries that have “Python” as the value for “Course”.
6.If there’s at least one dictionary in the list, return the first one.
7.If there’s no dictionary in the list, print “No matching dictionary found”.

Python3

from collections import defaultdict

test_list = [

    {'Course': "C++", 'Author': "Jerry"},

    {'Course': "Python", 'Author': "Mark"},

    {'Course': "Java", 'Author': "Paul"},

    {'Course': "Python", 'Author': "Kate"},

    {'Course': "Python", 'Author': "David"}

]

course_dict = defaultdict(list)

for d in test_list:

    course_dict[d['Course']].append(d)

filtered_list = course_dict['Python']

if len(filtered_list) > 0:

    filtered_dict = filtered_list[0]

    print(filtered_dict)

else:

    print("No matching dictionary found")

Output

{'Course': 'Python', 'Author': 'Mark'}

Time complexity:

The time complexity of this code is O(n), where n is the length of the test_list. This is because we iterate through the list once to create the defaultdict, which takes O(n) time. Then we access the list of dictionaries with “Python” as the value for “Course”, which takes O(1) time. Finally, we return the first dictionary in the list, which also takes O(1) time.

Space complexity:

The space complexity of this code is O(n), where n is the length of the test_list. This is because we create a defaultdict called course_dict that contains a list for each value of the “Course” key in the test_list. The size of course_dict is therefore proportional to the number of unique “Course” values in the test_list, which can be up to n in the worst case.

Last Updated :
26 Apr, 2023

Like Article

Save Article

  1. Используйте функцию next() для поиска в списке словарей в Python
  2. Поиск в списке словарей с помощью функции filter() в Python
  3. Использование понимания списка для поиска в списке словарей в Python

Поиск в списке словарей в Python

В этом руководстве представлены методы, которые вы можете использовать для поиска в списке словарей в Python.

Используйте функцию next() для поиска в списке словарей в Python

Функцию next() можно использовать для предоставления результата в качестве следующего элемента в данном итераторе. Этот метод также требует использования цикла for для проверки процесса на соответствие всем условиям.

Следующий код использует функцию next() для поиска в списке словарей в Python.

lstdict = [
        { "name": "Klaus", "age": 32 },
        { "name": "Elijah", "age": 33 },
        { "name": "Kol", "age": 28 },
        { "name": "Stefan", "age": 8 }
       ]
print(next(x for x in lstdict if x["name"] == "Klaus"))
print(next(x for x in lstdict if x["name"] == "David"))

Выход:

{'name': 'Klaus', 'age': 32}
Traceback (most recent call last):
  File "<string>", line 8, in <module>
StopIteration

Этот метод успешно реализуется, когда мы ищем имя, которое уже существует в списке словарей. Тем не менее, он выдает ошибку StopIteration при поиске имени, которого нет в списке словарей.

Однако эту проблему легко решить с помощью приведенного выше кода. Вы просто настраиваете и предоставляете значение по умолчанию с использованием немного другого API.

lstdict = [
        { "name": "Klaus", "age": 32 },
        { "name": "Elijah", "age": 33 },
        { "name": "Kol", "age": 28 },
        { "name": "Stefan", "age": 8 }
       ]
print(next((x for x in lstdict if x["name"] == "David"), None))

Выход:

Вместо того, чтобы искать сам элемент, мы также можем найти индекс элемента в Списке словарей. Для реализации этого мы можем использовать функцию enumerate().

Следующий код использует функцию next() и функцию enumerate() для поиска и нахождения индекса элемента.

lstdict = [
        { "name": "Klaus", "age": 32 },
        { "name": "Elijah", "age": 33 },
        { "name": "Kol", "age": 28 },
        { "name": "Stefan", "age": 8 }
       ]
print(next((i for i, x in enumerate(lstdict) if x["name"] == "Kol"), None))

Выход:

Поиск в списке словарей с помощью функции filter() в Python

Функция filter(function, sequence) используется для сравнения sequence с function в Python. Он проверяет, является ли каждый элемент в последовательности истинным или нет, в соответствии с функцией. Мы можем легко найти элемент в списке словарей, используя функцию filter() с функцией lambda. В Python3 функция filter() возвращает объект класса filter. Мы можем преобразовать этот объект в список с помощью функции list().

В следующем примере кода показано, как мы можем искать в списке словарей определенный элемент с помощью функций filter() и lambda.

listOfDicts = [
     { "name": "Tommy", "age": 20 },
     { "name": "Markus", "age": 25 },
     { "name": "Pamela", "age": 27 },
     { "name": "Richard", "age": 22 }
]
list(filter(lambda item: item['name'] == 'Richard', listOfDicts))

Выход:

[{'age': 22, 'name': 'Richard'}]

Мы провели поиск в списке словарей элемента, в котором ключ name равен Richard, используя функцию filter() с функцией lambda. Сначала мы инициализировали наш список словарей, listOfDicts, и использовали функцию filter() для поиска значений, которые соответствуют функции lambda lambda item: item['name'] == 'Richard' в Это. Наконец, мы использовали функцию list() для преобразования результатов в список.

Использование понимания списка для поиска в списке словарей в Python

Понимание списков – это относительно более короткий и очень изящный способ создания списков, которые должны формироваться на основе заданных значений уже существующего списка.

Мы можем использовать понимание списка, чтобы вернуть список, который производит результаты поиска списка словарей в Python.

Следующий код использует понимание списка для поиска по списку словарей в Python.

lstdict = [
        { "name": "Klaus", "age": 32 },
        { "name": "Elijah", "age": 33 },
        { "name": "Kol", "age": 28 },
        { "name": "Stefan", "age": 8 }
       ]

print([x for x in lstdict if x['name'] == 'Klaus'][0])

Выход:

{'name': 'Klaus', 'age': 32}

In this Python tutorial, we will study the implementation of Python Dictionary Search by value. Here we will see how to search for a value in Dictionary using some examples in python.

In Python, dictionaries are built-in data structure that stores key-value pairs. The keys in a dictionary must be unique, while the values can be of any data type.

There are a few different ways to get the key by value in a Python dictionary, depending on your specific use case.

  • Using the items()method
  • Using the list comprehension
  • Using the index() method
  • Using the filter() and lambda function

Method-1: Using the items() method

To get the key by value in a python dictionary is using the items() method and a for loop, items() method returns a view object that contains the key-value pairs of the dictionary, as tuples in a list.

# This code creates a dictionary called "countries" that contains the keys "USA", "Germany", and "France" 
# and the respective values 56, 25, and 78.
countries = {'USA': 56, 'Germany': 25,'France':78}

# The for loop iterates through the items in the dictionary, where "key" represents the key of each item 
# and "value" represents the value of each item.
for key, value in countries.items():
    # The if statement checks if the value of each item is equal to 56.
    if value == 56:
        # If the value is equal to 56, the key of that item is printed.
        print(key)

The above code outputs the USA as it is the key which has a value of 56.

Python Dictionary Search by value using items()
Python Dictionary Search by value using items()

Read: Python dictionary key error

Method 2: Using the list comprehension

This method iterates over the key-value pairs in the dictionary and uses a list comprehension to find the first key whose associated value is equal to the value you’re looking for.

# This code creates a dictionary called "my_dictionary" that contains keys and values 
# representing countries and their respective values.
my_dictionary = {'Newzealand': 567,
            'United Kingdom' : 456,
            'China': 945,
            'Japan': 845
            }
# The variable new_val is set to 456
new_val = 456
# A list comprehension is used to iterate through the items in the dictionary and check if the value of each item is equal to new_val.
# If the value is equal to new_val, the key of that item is added to the list.
result=[new_k for new_k in my_dictionary.items() if new_k[1] == new_val][0][0]
# The result is printed
print(result)

The code outputs “United Kingdom” as it is the key which have value 456.

Python Dictionary Search by value using list comprehension
Python Dictionary Search by value using list comprehension.

Read: Python Dictionary Count + Examples

Method-3: Using the index() method

The index() method is a built-in method in Python that is used to find the index of an element in a list. It takes a single argument, which is the element you want to find the index of and returns the index of the first occurrence of that element in the list.

# This code creates a dictionary called "my_dictionary" that contains keys and values 
# representing countries and their respective values.
my_dictionary = {'Newzealand': 567,
            'United Kingdom' : 456,
            'China': 945,
            'Japan': 845
            }

# Get the values from the dictionary as a list
values = list(my_dictionary.values())

# The variable new_val is set to 456
new_val = 456

# Find the index of the value in the list
index = values.index(new_val)

# Get the key from the dictionary using the index
result = list(my_dictionary.keys())[index]

# The result is printed
print(result)

The above code outputs “United Kingdom” as it is the key which has value 456 but uses the index() method of the list.

Python Dictionary Search by value using index() method.jpg
Python Dictionary Search by value using index() method.jpg

Read: Python Dictionary duplicate keys

Method-4: Using the filter() and lambda function

The lambda function is a small anonymous function that can be used to perform a certain operation, and the filter() function is used to filter a sequence of elements based on a certain condition.

# my_dictionary is a dictionary that contains keys as countries and values as their population
my_dictionary = {'Newzealand': 567,
            'United Kingdom' : 456,
            'China': 945,
            'Japan': 845
            }

# new_val is the population value for which we want to find the corresponding country
new_val = 456

# Using lambda and filter() functions to filter the items of the dictionary
# and only the items with the value of new_val are returned
result = list(filter(lambda x: x[1] == new_val, my_dictionary.items()))[0][0]

# The result is printed
print(result)

The above code outputs “United Kingdom” as it is the key that has value 456 but uses the filter() and lambda function.

Python Dictionary Search by value using filter and lambda function
Python Dictionary Search by value using filter and lambda function

You may also like to read the following Python tutorials.

  • Python Dictionary of sets
  • Python dictionary contains + examples
  • Python convert dictionary to list
  • Python dictionary filter + Examples

In this Python tutorial, we have covered how to get a key using the value of the dictionary by following the below methods.

  • Python Dictionary Search by value using the items() method
  • Python Dictionary Search by value using the list comprehension
  • Python Dictionary Search by value using the index() method
  • Python Dictionary Search by value using the filter() and lambda function

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

В этом посте будет обсуждаться, как искать значение для данного ключа в списке словарей в Python.

1. Использование выражения генератора

Простое решение — использовать выражение генератора. Это приведет к простому коду ниже:

if __name__ == ‘__main__’:

    dicts = [

        {“lang”: “Java”, “version”: “14”},

        {“lang”: “Python”, “version”: “3.8”},

        {“lang”: “C++”, “version”: “17”},

    ]

    key = “lang”

    val = “Python”

    d = next((d for d in dicts if d.get(key) == val), None)

    print(d)        # {‘lang’: ‘Python’, ‘version’: ‘3.8’}

Скачать  Выполнить код

2. Использование filter() функция

Другой способ поиска в списке словарей — использование filter() функция в Python 3.

if __name__ == ‘__main__’:

    dicts = [

        {“lang”: “Java”, “version”: “14”},

        {“lang”: “Python”, “version”: “3.8”},

        {“lang”: “C++”, “version”: “17”},

    ]

    key = “lang”

    val = “Python”

    d = next(filter(lambda d: d.get(key) == val, dicts), None)

    print(d)        # {‘lang’: ‘Python’, ‘version’: ‘3.8’}

Скачать  Выполнить код

Это все о поиске значения в списке словарей в Python.

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Добавить комментарий