This code works and does exactly what I want it to, but I feel that it is inelegant. It seems like there should be a way to use get() and/or setdefault(), for example. All comments and suggestions are appreciated!
Here is a function that builds a dict. The dict's values are also dicts. Some of the values are empty dicts {} and some are dicts that have a {key:value} pair.
def my_function(my_string, my_key):
d = {}
for i in range(3):
d['test' + str(i)] = {}
d['test3'] = {'a_key': 'a_value'}
# d = { 'test0': {}, 'test1': {}, 'test2': {}, 'test3': {'a_key': 'a_value'} }
if my_string != '':
d[my_key] = {my_string: None}
else:
# check if d[my_key] exists
try:
# d[my_key] exists and it is not empty, don't overwrite
if d[my_key]:
pass
# d[my_key] exists, but it is empty, write NULL
else:
my_string = 'NULL'
d[my_key] = {my_string: None}
# d[my_key] did not exist, create it and write NULL
except KeyError:
my_string = 'NULL'
d[my_key] = {my_string: None}
return d
# my_string not blank, my_key is new
f = my_function('hello', 'test4')
print(f)
# my_string not blank, my_key exists
f = my_function('hello', 'test0')
print(f)
# my_string blank, my_key exists and its value is not empty
f = my_function('', 'test3')
print(f)
# my_string blank, my_key exists and its value is empty
f = my_function('', 'test0')
print(f)
# my_string blank, my_key is new
f = my_function('', 'test4')
print(f)
Typical (and desired) output:
{'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {}, 'test1': {}, 'test4': {'hello': None}}
{'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {'hello': None}, 'test1': {}}
{'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {}, 'test1': {}}
{'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {'NULL': None}, 'test1': {}}
{'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {}, 'test1': {}, 'test4': {'NULL': None}}
def
and up to and includingreturn
should be indented one more tab, but I couldn't find an easy way to do that in the online editor. \$\endgroup\$