0

I want the value of id 1400 how to get it ?

 x = {'type': 'Asset', 'id': 1400}

OUTPUT SHOULD BE

1400
  • Welcome to Stack Overflow. It is a programming help site, but first you need to try to do it yourself, and we'll help you get through that. To learn how to ask good questions you can read https://stackoverflow.com/help/how-to-ask This question will most likely be deleted for being too broad – Mikkel Sep 16 '17 at 15:06

3 Answers3

2

The simplest way is using square bracket notation. But be careful if the element is not found it will throw and exception.

x['id']

A more flexible way would be with the .get() method.

x.get('id')

The difference is that with .get() you can pass a default value.

x.get('id', 0)

And you can do some more complex navigation. For example:

x.get('y', {}).get('z', None)

This would try to get y. If it can't find it it will return an empty dict from which it will try to get z. If it can't find it, it will return None without throwing an exception.

l4sh
  • 321
  • 2
  • 7
1

x in your example is a dictionary. In python, you access dictionary items via their key, which in this case is "id".

output = x["id"]

If you attempt to use a key which does not exist in the dictionary, you will get a KeyError. If you are unsure if the key you will be using is in the dictionary, you can either use a try-except:

try:
    output = x["id"]
except KeyError:
    #Handle error

Or, you can use .get() to provide a default value. If the key you use does not exist in the dictionary, the default value is returned and no exception is raised.

output = x.get("id", default_value)

If you omit default_value, then None is returned if the key does not exist.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
1

You can also do, x.get("id"). In this case, you wont get KeyError Exception in case id isn't in the dict.