1
function getParams(data) {
    return {
        id: data && data.uuid
    }
}

So the above represents a common pattern in Javascript for accessing the items of an object.

What is the most commonly used equivalent practice in Python for accessing items of a dict?

Would it be like so?

def getParams(data):
    params = {}
    if data is not None and hasattr(data, "id"):
        params["id"] = data["id"]
    return params

If not, what is the best practice? Thanks.

r123454321
  • 3,323
  • 11
  • 44
  • 63

4 Answers4

5

If you want to get a key from a dict without knowing if it's there, you can use the get method of dicts. It returns None (or a specific default value) if the key isn't there:

>>> x = {}
>>> print(x.get('a'))
None
>>> print(x.get('a', 'default'))
default
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Gotcha. What is the traditional thing to do if I want to check an item in a nested dictionary? i.e. Javascript equivalent would be: – r123454321 Jan 02 '16 at 08:09
  • `data && data.uuid && data.uuid.someAttribute` – r123454321 Jan 02 '16 at 08:09
  • @RyanYu: You can use `get` multiple times, like `data.get('uuid', {}).get('someAttribute', None)`. But also look around on this site for other people asking similar questions, there are many. – BrenBarn Jan 02 '16 at 08:12
  • Although `get` is convenient, be aware that it can be noticeably slower than more verbose code that uses `in`. – PM 2Ring Jan 02 '16 at 08:41
3

If you mean attributes:

params['id'] = data.id if data else None

If you mean items:

params['id'] = data.get('id')

In both cases params['id'] will contain value or None.

Daniel
  • 42,087
  • 4
  • 55
  • 81
Eugene Primako
  • 2,767
  • 9
  • 26
  • 35
0

Python dict is different from javascript.

def getParams(data):
    params = {}
    if data and 'id' in data.keys():
        params["id"] = data["id"]
    return params
kia
  • 828
  • 5
  • 12
  • 3
    If you want to check, that an item is in a dictionary, use `'id' in data`. Key checking is a key feature of dicts. – Daniel Jan 02 '16 at 08:05
  • What Daniel said. `'id' in data.keys()` is wasteful because it has to construct the keys object. That's not so bad in Python 3 because it's a [dictionary view object](https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects) that accesses the underlying `dict`; and look-ups on dictviews are fast. But in Python 2 `dict.keys()` has to build a new list object, and lookups on a list involve a slow linear search rather than the fast O(1) lookup that a dictionary or set provides. – PM 2Ring Jan 02 '16 at 08:37
0

You can use get method of dict. A default value can also be specified, which could be used if the specified key do not exist.

data.get('id', None)
aliasm2k
  • 883
  • 6
  • 12