我相信你想把字典弄平?
(改编自https://stackoverflow.com/a/6027615/3622606)
import collections
def flatten(d, parent_key='', sep='.'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(flatten(v, new_key).items())
else:
items.append((new_key, v))
return dict(items)
dictionary = {"a": {"one": "b"}, "c" : {"title": "cool", "challenge": {"win": "score", "lose":"don't score"}}}
flattened_dict = flatten(dictionary)
# Returns the below dict...
# {"a.one": "b", "c.title": "cool", "c.challenge.win": "score", "c.challenge.lose": "don't score"}
# And now print them out...
for value in flattened_dict:
print '"%s" = "%s"' % (value, flattened_dict[value])
# "c.challenge.win" = "score"
# "c.title" = "cool"
# "a.one" = "b"
# "c.challenge.lose" = "don't score"