How to convert the following code into a nested comprehensions?
new_dict = {'Accounts': 'lbl1', 'Inventory': 'lbl2', 'Manufacture': 'lbl3', 'PayRoll': 'lbl4', 'kannagu': 'lbl1', 'Saragu': 'lbl2', 'Thayarippu': 'lbl3', 'Sambalam': 'lbl4', 'F1': 'lbl1', 'F2': 'lbl2', 'F3': 'lbl3', 'F4': 'lbl4'}
dict_keys = {'name': {'lbl1': 'label1', 'lbl2': 'label2', 'lbl3': 'label3', 'lbl4': 'label4'}, 'item3': {'lbl1': 'F1', 'lbl2': 'F2', 'lbl3': 'F3', 'lbl4': 'F4'}, 'item2': {'lbl1': 'kannagu', 'lbl2': 'Saragu', 'lbl3': 'Thayarippu', 'lbl4': 'Sambalam'}, 'item1': {'lbl1': 'Accounts', 'lbl2': 'Inventory', 'lbl3': 'Manufacture', 'lbl4': 'PayRoll'}, 'printitem': {'lbl1': 'You clicked label1', 'lbl2': 'You clicked label2', 'lbl3': 'You clicked label3', 'lbl4': 'You clicked label4'}}
for key,val in new_dict.items():
if key == Accounts:
for k, v in dict_key['printitem'].items():
if k == val :
print(v)
>Solution :
Dictionary comprehensions are useful for creating a dictionaries compactly. They need to result in a new dictionary, and they shouldn’t have side effects like printing values. This code doesn’t create a dictionary, so they’re not suitable here.
You actually don’t need either of the loops. Both of them are just looking up a key in a dictionary, which can be done with a simple d[key] or d.get(key) lookup. You can simplify this code to:
if val := new_dict.get(sending_button.text()):
if v := dict_key['printitem'].get(val):
print(v)
If you’re not using Python 3.8 then you can use this longer version without the := walrus operator:
val = new_dict.get(sending_button.text())
if val:
v = dict_key['printitem'].get(val)
if v:
print(v)