Home > Software engineering >  How to create a nested dictionary through normal iterating?
How to create a nested dictionary through normal iterating?

Time:06-04

How to convert a default available dictionary to our desired format based on some conditions.

language = {"english" : {"lbl01":"File"      ,"lbl02":"Accounts"},
            "tamil"   : {"lbl01":"கோப்பு"    ,"lbl02":"கணக்கியல்"},
            "Hindi"   : {"lbl01":"Hindi_File","lbl02":"Hindi_accounts"}}

selected_lan =["english","tamil"]

For example: From the above default dictionary, I want to create a new dictionary in the following format, In my case, I select the first language as English and the second language as Tamil:

{'lbl01': {'english': 'File', 'tamil': 'கோப்பு'}, 'lbl02': {'english': 'Accounts', 'tamil': 'கணக்கியல்'}}

I try the following code and its output is as follows :,

lan_dict_1 = {}
for n,d in language.items():
    if n in selected_lan:
        for i,j in d.items():
            lan_dict_1={n:d[i]}
            print(lan_dict_1)

Output

{'english': 'File'}
{'english': 'Accounts'}
{'tamil': 'கோப்பு'}
{'tamil': 'கணக்கியல்'}

How to achieve it, in normal looping and as well as in the comprehension method?

CodePudding user response:

You can use pandas:

import pandas as pd
pd.DataFrame(language).T.to_dict() 

{'lbl01': {'english': 'File', 'tamil': 'கோப்பு', 'Hindi': 'Hindi_File'},
 'lbl02': {'english': 'Accounts',
  'tamil': 'கணக்கியல்',
  'Hindi': 'Hindi_accounts'}}

If you want to use the selected_lan:

selected_lan =["english","tamil"]
pd.DataFrame(language)[selected_lan].T.to_dict()

{'lbl01': {'english': 'File', 'tamil': 'கோப்பு'},
 'lbl02': {'english': 'Accounts', 'tamil': 'கணக்கியல்'}}

For a normal loop:

d = {}
selected_lan =["english","tamil"]
for lan, vals in language.items():
    for idx, typ in vals.items():
        if d.get(idx) is None:
            d[idx] = {}
        if lan in selected_lan:
            d[idx].update({lan:typ})
print(d)
        

{'lbl01': {'english': 'File', 'tamil': 'கோப்பு'},
 'lbl02': {'english': 'Accounts', 'tamil': 'கணக்கியல்'}}

CodePudding user response:

Alternative :

language = {"english" : {"lbl01":"File"      ,"lbl02":"Accounts"},
        "tamil"   : {"lbl01":"கோப்பு"    ,"lbl02":"கணக்கியல்"},
        "Hindi"   : {"lbl01":"Hindi_File","lbl02":"Hindi_accounts"}}
        

select = ["english","tamil"]

labels = language['english'].keys() # ['lbl01', 'lbl02']

output = dict( zip ( 
    labels, 
    map( lambda label: {sel:language[sel][label] for sel in select}, labels )
) )

print( output )

Or this which ever you prefer :

output = {
    lab: {sel:language[sel][lab] for sel in select}
    for lab in labels
}

CodePudding user response:

Alternative just using a for looping:

language = {"english" : {"lbl01":"File"      ,"lbl02":"Accounts"},
            "tamil"   : {"lbl01":"கோப்பு"    ,"lbl02":"கணக்கியல்"},
            "Hindi"   : {"lbl01":"Hindi_File","lbl02":"Hindi_accounts"}}

selected_lan =["english","tamil"]

lan_dict_1 = {}
keys = list(language[selected_lan[0]].keys())
for sec_key in keys:
  sec_dicts = {}
  for key in selected_lan:
    sec_dicts[key] = language[key][sec_key]
    lan_dict_1[sec_key] = sec_dicts

Here is the example running in real time:

https://abstra.show/P3BQoFskIn

  • Related