How to get a false-like value instead of error when retrieving non-existent elements in lists or dictionaries in Python

Th31AndOnly

I would like to know how to, instead of getting an error, return a False-like value when trying to access a list out of range, for example, or trying to grab a key from a dictionary that doesn't exist. Does anyone know of a method?

Dalvenjia

for a dictionary you can use a defaultdict from the collections module I.E:

from collections import defaultdict

my_dict = defaultdict(lambda: False)

my_dict['test']  # This will be False

You can read more about defaultdict in the docs

For a list however it gets a bit more complicated, sublcassing list and overriding the __getitem__ method to wrap the call in a try/except clause and return a different value:

class defaultlist(list):
    def __getitem__(self, key):
        try:
            return super().__getitem__(key)
        except IndexError:
            return False

my_list = defaultlist()
my_list[10]  # This will be False

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

error status from popen when the command accesses a non existent file

Get intersection elements of nested dictionaries in Python

How does == comparison of 2 dictionaries work when the value is a mutable type like list (does order matter)?

In Python How to get List of Lists from String that looks like List of Lists

Python Dictionaries and Lists

Python Dictionaries with lists from user input how to solve this?

Python - remove non-unique elements between lists

How to restrict the number of elements in python lists

Python Selenium: How to get elements from multiple html lists of undefined length that have the same relative xpath?

How to get name of an option value when validation returns false in laravel 5

How to get a sign instead of a value in html?

How to GET actors that containing nationality like argentine sort by fullName: error when typing in url postman

Two python lists to nested dictionaries repeating pattern

Create Dictionary Of Lists from List of Dictionaries in Python

Creating a list of dictionaries from a list of lists in Python

python appending dictionaries to lists causes keyError

parsing 3 lists into list of dictionaries in python

SQLite in memory with dapper generates non-existent table error

How to return True/False instead of 1/0 in python

Python - how to get all the values of nested dictionaries as a single List[dict]?

how to get value(python)

How to succinctly name all elements of several lists the same when the lists are nested in an R list?

Excel - When enter a value: error instead of locked cell

Python: for a list of lists, get mean value in each position

how to get index range for zero and non-zero value from list in python?

list of dictionaries, how to get: intersection based on one value and symmetric difference based on another value

Concatenate elements of two lists in Python

Python: PDF: How to read from form elements like checkbox

How to recursively get scalar value from 2 lists?

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    Как не использовать HttpClient с ЛЮБЫМ сертификата SSL, независимо от того, как «плохо» это

  3. 3

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  4. 4

    Elasticsearch - Нечеткий поиск не дает предложения

  5. 5

    Modbus Python Schneider PM5300

  6. 6

    Автозаполнение с Java, Redis, Elastic Search, Монго

  7. 7

    Ошибка «LINK: фатальная ошибка LNK1123: сбой при преобразовании в COFF: файл недействителен или поврежден» после установки Visual Studio 2012 Release Preview

  8. 8

    (fields.E300) Поле определяет связь с моделью, которая либо не установлена, либо является абстрактной.

  9. 9

    Проблемы со сборкой Python Image Registration Toolkit

  10. 10

    Vue js CLI 2 импортирует и использует плагин javascript

  11. 11

    Как отправить файл с сообщением в Discord с помощью JDA?

  12. 12

    В чем разница между CRC-16 / CCITT-FALSE и CRC-16 / X-25?

  13. 13

    Single legend for Plotly subplot for line plots created from two data frames in R

  14. 14

    Vim - автокоманды игнорируются в коде автокоманд

  15. 15

    Метод ошибки Illuminate \\ Database \\ Eloquent \\ Collection :: save не существует. в Laravel

  16. 16

    Статус HTTP 403 - ожидаемый токен CSRF не найден

  17. 17

    Ленивое объединение FPU в Cortex-M4F

  18. 18

    Работа с отсутствующими значениями для одной переменной в R

  19. 19

    Как очистить или очистить StringBuilder?

  20. 20

    PyQt5 не работает как «подходящий UI Toolkit» для Mayavi с Python 3.6.

  21. 21

    Vue 2 с Vue CLI - как сделать src / static static, чтобы я мог использовать изображения, которые там есть?

популярныйтег

файл