I’d like to create a dictionary inside a dictionary in python using function setdefault().
I’m trying to make a list of names and dates of birth using fallow dictionary.
names = {'Will': 'january', 'Mary': 'february', 'George': 'march', 'Steven': 'april', 'Peter': 'may'}
dates = {'Will': '7/01', 'George': '21/03', 'Steven': '14/03', 'Mary': '2/02'}
I was tring to use set to achieve this:
res_dict = dict()
for v, k in names.items():
for v1, k1 in dates.items():
res_dict.setdefault(v, {}).append(k)
res_dict.setdefault(v1, {}).append(k1)
return res_dict
but it give me an error.
The result should be:
res_dict = {'Will': {'january': '7/01'}, 'Mary' : {'february': '2/02'} ,'George': {'march': '21/03'}, 'Steven': {'april': '14/03'}, 'Peter': {'may': ''}}
How can I get the desired result using setdefault()?
You could try this:
And as to your comment regarding adding
monthandday, you can add them similarly:And if you want to omit
daycompletely in the case where a value doesn’t exist:And in the odd case where you know the date but not the month, iterating through the set of the keys (as @KayZhu suggested) with a
defaultdictmay be the easiest solution: