I want the value of id 1400 how to get it ?
x = {'type': 'Asset', 'id': 1400}
OUTPUT SHOULD BE
1400
I want the value of id 1400 how to get it ?
x = {'type': 'Asset', 'id': 1400}
OUTPUT SHOULD BE
1400
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.
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.
You can also do, x.get("id"). In this case, you wont get KeyError Exception in case id isn't in the dict.