Check if parent dict is not empty and retrieve the value of the nested dict

2024/10/11 0:26:37

Let's suppose that I have a nested dictionary which looks like that:

parent_dict = { 'parent_key': {'child_key': 'child_value'}

How can I write the following code:

if parent_dict.get('parent_key') is not None and parent_dict['parent_key']['child_key']=='value_1':print('Value detected')

in a more efficient way in terms of readability and amount of code?

Specifically I think that the first if condition could be somehow integrated with the second one in one condition.

So for I would like it to be like that:

if condition_x:print('Value detected')

where condition_x checks both if the parent dict is not empty and if not then it returns the value of the child dict otherwise it returns None.

Answer

you could use the dict.get method:

if parent_dict.get('parent_key', {}).get('child_key') == 'value_1':...

dict.get(key) will return dict[key] if the key exists; otherwise it will return None.dict.get(key, default) will return default if the key does not exist. setting the default value to an empty dict {} will make the second .get work.

https://en.xdnf.cn/q/118388.html

Related Q&A

List combinations in defined range

I am writing parallel rainbow tables generator using parallel python and multiple machines. So far, I have it working on a single machine. It creates all possible passwords, hashes them, saves to file.…

Python turtle drawing a symbol

import turtlewin=turtle.Screen()t = turtle.Turtle() t.width(5)#The vertical and horizontal lines t.left(90) t.forward(70) t.left(90) t.forward(20)t.left(90) t.forward(60) t.left(120) t.forward(35) t.b…

Display a countdown for the python sleep function in discord embed in python

hi all I am doing one discord bot I need to send one countdown its like a cooldown embed after every request I did this code but I dont know how to add this in my embedfor i in range(60,0,-1):print(f&q…

Bypass rate limit for requests.get

I want to constantly scrape a website - once every 3-5 seconds withrequests.get(http://www.example.com, headers=headers2, timeout=35).json()But the example website has a rate limit and I want to bypass…

ValueError when using if commands in function

Im creating some functions that I can call use keywords to call out specific functions,import scipy.integrate as integrate import numpy as npdef HubbleParam(a, model = "None"):if model == &qu…

Python consecutive subprocess calls with adb

I am trying to make a python script to check the contents of a database via adb. The thing is that in my code,only the first subprocess.call() is executed and the rest are ignored. Since i am fairly ne…

Django Page not found(404) error (Library not found)

This is my music\urls.py code:-#/music/ url(r^/$, views.index, name=index),#/music/712/ url(r^(?P<album_id>[0-9]+)/$, views.detail, name=detail),And this is my views.py code:-def index(request):…

Django. Create object ManyToManyField error

I am trying to write tests for my models.I try to create object like this:GiftEn.objects.create(gift_id=1,name="GiftEn",description="GiftEn description",short_description="Gift…

No module named discord

Im creating a discord bot, but when I try to import discord, I am getting this error: Traceback (most recent call last):File "C:\Users\Someone\Desktop\Discord bot\bot.py", line 2, in <modu…

Calendar with tkinter (print the selected date)

I got this code online in order to create a calendar with tkinter:""" Simple calendar using ttk Treeview together with calendar and datetime classes. """ import calendar i…