Python map get or default

using python default dictionary vs .get()

I want a dictionary with default to None. I have two ways to implement: 1) use collections.defaultdict and set default value to None. https://docs.python.org/2/library/collections.html 2) use an ordinary dictionary but use .get() to get the value. When the key does not exist, by default it returns None. Which way is better?

As usual, the answer to «which is better?» is «that depends». These approaches have tradeoffs. What do you need it for?

2 Answers 2

defaultdict will use more memory than dict.get() since if no key found, defaultdict will set the default value in wrapped dict with the key.

on the other hand, dict.get() just return the default value directly if no key found in dict. No extra space needed.

Running 0.2 billion with empty dict using python2,

200000000 199.584 0.000 283.804 0.000 default.py:11(get_default) 200000000 158.268 0.000 158.268 0.000 default.py:14(get_defaultdict) 

The memory usage when running 1 million data with empty dict using python2,

Line # Mem usage Increment Line Contents ================================================ 17 10.918 MiB 10.918 MiB @profile 18 def run_get_default(): 19 10.918 MiB 0.000 MiB h = <> 20 10.918 MiB 0.000 MiB for i in xrange(0, COUNT): 21 10.918 MiB 0.000 MiB get_default(h, i) 22 10.918 MiB 0.000 MiB get_default(h, i) Line # Mem usage Increment Line Contents ================================================ 24 10.918 MiB 10.918 MiB @profile 25 def run_get_defaultdict(): 26 10.918 MiB 0.000 MiB h = defaultdict(int) 27 83.496 MiB 7.273 MiB for i in xrange(0, COUNT): 28 83.496 MiB 58.141 MiB get_defaultdict(h, i) 29 83.496 MiB 7.164 MiB get_defaultdict(h, i) 

defaultdict needs a callable value as the dict default value, you can also use the function or lambda to customize your own default value per requirement

Читайте также:  Javascript позиция в строке

dict.get($key, $default) is easier to get the default per record

Источник

Not using get() to return a default value from a dict¶

Frequently you will see code create a variable, assign a default value to the variable, and then check a dict for a certain key. If the key exists, then the value of the key is copied into the value for the variable. While there is nothing wrong this, it is more concise to use the built-in method dict.get(key[, default]) from the Python Standard Library. If the key exists in the dict, then the value for that key is returned. If it does not exist, then the default value specified as the second argument to get() is returned. Note that the default value defaults to None if a second argument is not provided.

Anti-pattern¶

The code below initializes a variable called data to an empty string. Then it checks if a certain key called message exists in a dict called dictionary . If the key exists, then the value of that key is copied into the data variable.

Although there is nothing wrong with this code, it is verbose and inefficient because it queries the dictionary twice. The solution below demonstrates how to express the same idea in a more concise manner by using dict.get(key[, default]) .

dictionary = "message": "Hello, World!"> data = "" if "message" in dictionary: data = dictionary["message"] print(data) # Hello, World! 

Best practice¶

Use dict.get(key[, default]) to assign default values¶

The code below is functionally equivalent to the original code above, but this solution is more concise.

When get() is called, Python checks if the specified key exists in the dict. If it does, then get() returns the value of that key. If the key does not exist, then get() returns the value specified in the second argument to get() .

dictionary = "message": "Hello, World!"> data = dictionary.get("message", "") print(data) # Hello, World! 

References¶

Источник

Python map with default arguments

Yes, because map() wasn’t intended to have the argument passed to different keyword parameters. If you would always pass the numbers to foo and you’d have bar=1 as parameter with default argument then we’d have a valid use of map() .

@MikeVella, you accepted mtitan8 answer, but in my view it gives not the output asked by your question and pseudo code. Please clarify what exactly did you want to achieve (see my answer for example, when output of sample fn is provided)

3 Answers 3

You could use lambda to wrap the function with the default parameters:

map(lambda x: fn(x, bar=[1, 2, 3]), range(5)) 

Thanks, There were several excellent answers but I found yours to be my preferred one because it relies on no external modules and just «feels» right.

For sake of correctnes, it seems that partial usage should be

>>> from functools import partial >>> def fn(foo=0,bar=1): . print 'foo <>, bar <>'.format(foo, bar) . >>> foo = [1,2,3] >>> bar = [4,5,6] >>> map(fn, foo) foo 1, bar 1 foo 2, bar 1 foo 3, bar 1 [None, None, None] >>> map(partial(fn, 0), bar) foo 0, bar 4 foo 0, bar 5 foo 0, bar 6 [None, None, None] 

It’s better to use list comprehension I think

as for map the only way I can propose You is function which will call your function with expected keyword argument

either dedicated function

def wrapper(func, kw): def wrapped(a): return func(**) return wrapped map(wrapper(foo, 'bar'), [1, 2, 3]) # if keyword argument is the same far all calls 
map(lambda x: foo(bar=x), range(5)) # if keyword argument is the same far all calls map(lambda x: foo(**), ['bar', 'foo', 'bar'], range(3)) # if keyword arguments are different all calls 

Источник

HashMap in Python

This is a HashMap implementation written in Python. All the methods are based on the java implementation of a HashMap . Any and all critique is welcome. This implementation is just a rewrite of some java HashMap methods. Yes, it’s basically a wrapper class for pythons dict . This implementation is a simple exercise to see if I could write something from Java in Python.

from typing import Union, List class HashMap: def __init__(self): self.capacity = 16 self.map = <> def clear(self) -> None: """ Clears all the entries into this hashmap :return: None """ self.map = <> def contains_key(self, key: object) -> bool: """ Returns if the map contains the passed key :param key -> object: Value to check residency in map keyset :return bool: True if "key" in map keyset, False otherwise """ return key in self.map.keys() def contains_value(self, value: object) -> bool: """ Returns if the map contains the passed value :param value -> object: Value to check residency in map valueset :return bool: True if "value" in map valueset, False otherwise """ return value in self.map.values() def entry_set(self) -> set: """ Returns a set of the hashmap :return set: A set representation of the map """ return set(self.map) def get(self, key: object) -> Union[object, None]: """ Returns the value at the passed key, None if not present :param key -> object: Key to retrieve value in map :return Union[object, None]: value at "key", None if key is not present in map """ return self.mapPython map get or default if key in self.map.keys() else None def get_or_default(self, key: object, default_value: object) -> object: """ Returns the value at the passed key, or default_value if not present :param key -> object: Key to retrieve value in map\n :param default_value -> object: Value to return if key is not present in map :return object: Value associated with "key", "default_value" otherwise """ return self.mapPython map get or default if key in self.map.keys() else default_value def is_empty(self) -> bool: """ Returns if the map has no key-value entries :return bool: True if map isn't empty, False otherwise """ return self.map != <> def key_set(self) -> set: """ Returns a set of all the keys :return set: Set of all keys in map """ return set(self.map.keys()) def put(self, key: object, value: object) -> object: """ Adds the key-value pair to the map, returning the value :param key -> object: Key to add to set\n :param value -> object: Value to add to set :return object: "value" passed """ self.mapPython map get or default = value return value def remove(self, key: object) -> Union[object, None]: """ Removes the mapping for the passed key, returning the value :param key -> object: Key to retrieve value from map :return object: Value associated with "key", None if key not in map keyset """ if key in self.map.keys(): value = self.mapPython map get or default del self.mapPython map get or default return value return None def size(self) -> int: """ Returns the size of the hashmap :return int: Size of map """ return len(self.map) def values(self) -> List[object]: """ Returns a list of the values in the hashmap :return List[object]: List of values in map """ return list(self.map.values()) 
if __name__ == "__main__": hashmap = HashMap() hashmap.put("Ben", 18) hashmap.put(5, 18) hashmap.put("5", True) hashmap.put(False, 3.661) print(hashmap.get(5)) print(hashmap.get(False)) print(hashmap.get("Ben")) print(hashmap.size()) print(hashmap.values()) 

Источник

Python Guy

I have seen a lot of Python code, as well as Java, Perl, and other languages. When dealing with dicts, I have identified a few patterns that I feel are optimal, depending on the situation. These are extraordinarily simple.

NOTE: The dict data structure is known by many names: map, a hashmap, an associative array, a hash, or even a table.

Use if Present

For instance, how many times have you written the following pseudo-code in your language of choice?

# pseudo-code if key is in map: lookup value in map with key use value

Python provides the “get()” method which returns None if it is not present.

# Python value = map.get(key) if value is not None: # use value

Of course, sometimes you need to distinguish between values that are None and that are not present in the dict. You can rely on exceptional behavior for this:

# Python try: value = mapPython map get or default except KeyError: pass else: # use value

Or you can use the “in” test:

# Python if key in map: value = mapPython map get or default # use value

The above, of course, does 2 dict lookups.

Exceptions versus Lookups

There is discussion about whether to use exceptions or lookups. The general rule of thumb is that exceptions are not as slow as you think, since Python is pretty slow to begin with. “Slow”, of course, is a relative term that is meaningful when you compare Python to C/C++. And nowadays with PyPy, “slow” isn’t a proper word for it anymore.

Use Value or Default If Missing

Sometimes you want to use a default value if the key is not present. This is simply:

# Python value = map.get(key, 'default')

Note that whatever expression you use as the default value will be evaluated, whether or not it was used. If the expression is expensive to calculate, then you can use this form:

# Python value = map.get(key) if value is None: value = expensive_expression()

Notice that you’re back to the previous pattern if you need to distinguish between a value of None and a missing key.

Use Value or Default and Store if Missing

Sometimes you want to store the default value in the dict if it is missing. “setdefault()” is the ideal method for this.

# Python value = map.setdefault(key, 'default')

Of course, the caveats for expensive default expressions applies.

Conclusion and Summary

Those of you who are unfamiliar with Python might note how similar all of the above patterns are. Indeed, if you simply learn what the following expressions mean, you don’t have to think very hard to understand what the code does or to choose the right code:

  • key in dict
  • dictPython map get or default
  • dict.get(key)
  • dict.get(key, default)
  • dict.setdefault(key, default)

Источник

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