So, the first requirement was to print the key 'a' from d1, which was very simple.
The second one was to get the key 'c' from d1, which doesn't exist. And if doesn't exist return the 0. This one I solved with get.
d1 = {'a': 1, 'b': 2, 'd': 5}
d2 = {'a': 1, 'b': 2, 'c': {'d': 4}}
print(d2.get('a', 0))
- The third requirement was to print the value assigned to 'd' from d2.
As you can see, 'c':{'d':4}
. C contains a little dict merged in the main one. Or something like that.
Is there a possibility to print the key value of 'd'?
CodePudding user response:
Well "akchually", there is no "d" key in d2
.
However if you type:
print(d2['c']['d'])
you will get what you want.
CodePudding user response:
The .get()
method for dictionaries has a optional parameter for a default value if the key is not found: dictionary.get(key, default)
Since a value could technically be 0, even though the default value is 0, you could test the type of the result in a if/else.
Using a loop and default values you can return whatever data you want, such as this:
d1 = {'a': 1, 'b': 2, 'd': 5}
d2 = {'a': 1, 'b': 2, 'c': {'d': 4}}
for item in [d1,d2]:
print(item)
print("value of 'a':", item.get('a', 0))
c_value = item.get('c', 0)
if type(c_value) == dict:
print("value of dictionary in 'c':", item['c'].get('d'))
else:
print("value of 'c':", c_value)
print("value of 'd':", item.get('d', 0))
print()
Resulting in:
{'a': 1, 'b': 2, 'd': 5}
value of 'a': 1
value of 'c': 0
value of 'd': 5
{'a': 1, 'b': 2, 'c': {'d': 4}}
value of 'a': 1
value of dictionary in 'c': 4
value of 'd': 0