Python functions in dict

Why store a function inside a python dictionary?

I’m a python beginner, and I just learned a technique involving dictionaries and functions. The syntax is easy and it seems like a trivial thing, but my python senses are tingling. Something tells me this is a deep and very pythonic concept and I’m not quite grasping its importance. Can someone put a name to this technique and explain how/why it’s useful? The technique is when you have a python dictionary and a function that you intend to use on it. You insert an extra element into the dict, whose value is the name of the function. When you’re ready to call the function you issue the call indirectly by referring to the dict element, not the function by name. The example I’m working from is from Learn Python the Hard Way, 2nd Ed. (This is the version available when you sign up through Udemy.com; sadly the live free HTML version is currently Ed 3, and no longer includes this example). To paraphrase:

# make a dictionary of US states and major cities cities = # define a function to use on such a dictionary def find_city (map, city): # does something, returns some value if city in map: return map[city] else: return "Not found" # then add a final dict element that refers to the function cities['_found'] = find_city 

Then the following expressions are equivalent. You can call the function directly, or by referencing the dict element whose value is the function.

>>> find_city (cities, 'New York') NY >>> cities['_found'](cities, 'New York') NY 

Can someone explain what language feature this is, and maybe where it comes to play in «real» programming? This toy exercise was enough to teach me the syntax, but didn’t take me all the way there.

Читайте также:  Css image borders styles

Источник

Python functions in dict

Pro pythonistas will tell you that you should actually be using python with higher order functions & as first class functions. Passing around functions are any programming languages greatest attribute. Here’s a trick to making function calls using python dictionaries.

Consider you have some functions add , subtract , divide and multiply . You could call these functions from a python dictionary like so:

def add(x, y): return x+y def subtract(x, y): return x-y def divide(x, y): return x/y def multiply(x, y): return x*y x, y = 20, 10 operations =  'add': add, 'subtract': subtract, 'divide': divide, 'multiply': multiply, > # add variables x & y print operations['add'](x, y) # 30 # subtract variables x & y print operations['subtract'](x, y) # 10 # divide variables x & y print operations['divide'](x, y) # 2 # multiply variables x & y print operations['multiply'](x, y) # 100

To use variable size of arguments you could call the operations dictionary with *args

def add(*args): total = 0 for i in args: total += i return total def subtract(x, y): return x-y x, y, z = 20, 10, 5 p, q, r = 30, 40, 50 operations =  'add': add, 'subtract': subtract > # add variables x, y, z, p, q, r print operations['add'](x, y, z, p, q, r) # 155 # subtract variables x & y print operations['subtract'](x, y) # 10

I would love to hear what you think about this post, also know about your tricks to using python in the comments below.

I am writing a book!

While I do appreciate you reading my blog posts, I would like to draw your attention to another project of mine. I have slowly begun to write a book on how to build web scrapers with python. I go over topics on how to start with scrapy and end with building large scale automated scraping systems.

If you are looking to build web scrapers at scale or just receiving more anecdotes on python then please signup to the email list below.

Источник

Словари (dict) и работа с ними. Методы словарей

Python 3 логотип

Сегодня я расскажу о таком типе данных, как словари, о работе со словарями, операциях над ними, методах, о генераторах словарей.

Словари в Python — неупорядоченные коллекции произвольных объектов с доступом по ключу. Их иногда ещё называют ассоциативными массивами или хеш-таблицами.

Чтобы работать со словарём, его нужно создать. Сделать это можно несколькими способами. Во-первых, с помощью литерала:

Во-вторых, с помощью функции dict:

В-третьих, с помощью метода fromkeys:

В-четвертых, с помощью генераторов словарей, которые очень похожи на генераторы списков.

Теперь попробуем добавить записей в словарь и извлечь значения ключей:

  : Как видно из примера, присвоение по новому ключу расширяет словарь, присвоение по существующему ключу перезаписывает его, а попытка извлечения несуществующего ключа порождает исключение. Для избежания исключения есть специальный метод (см. ниже), или можно перехватывать исключение.

Что же можно еще делать со словарями? Да то же самое, что и с другими объектами: встроенные функции, ключевые слова (например, циклы for и while), а также специальные методы словарей.

Методы словарей

dict.clear() — очищает словарь.

dict.copy() — возвращает копию словаря.

classmethod dict.fromkeys(seq[, value]) — создает словарь с ключами из seq и значением value (по умолчанию None).

dict.get(key[, default]) — возвращает значение ключа, но если его нет, не бросает исключение, а возвращает default (по умолчанию None).

dict.items() — возвращает пары (ключ, значение).

dict.keys() — возвращает ключи в словаре.

dict.pop(key[, default]) — удаляет ключ и возвращает значение. Если ключа нет, возвращает default (по умолчанию бросает исключение).

dict.popitem() — удаляет и возвращает пару (ключ, значение). Если словарь пуст, бросает исключение KeyError. Помните, что словари неупорядочены.

dict.setdefault(key[, default]) — возвращает значение ключа, но если его нет, не бросает исключение, а создает ключ со значением default (по умолчанию None).

dict.update([other]) — обновляет словарь, добавляя пары (ключ, значение) из other. Существующие ключи перезаписываются. Возвращает None (не новый словарь!).

dict.values() — возвращает значения в словаре.

Для вставки кода на Python в комментарий заключайте его в теги

Источник

Оцените статью