Reputation: 87
I have a nested dictionary where the lowest level consists of a list with one element each. I want to change this level from list to string. Assume I have a dictionary such as this:
dict = {id1:{'key11':['value11'],'key12':['value12']}, id2:{'key21':['value21'],'key22':['value22']}}
How can I get:
dict = {id1:{'key11': 'value11','key12':'value12'}, id2:{'key21':'value21','key22':'value22'}}
Additional question: How does the solution change if the keys and values do not follow a certain logic but each element is unique and you have many of them; such as in the below example:
dictionary = {'ida':{'abc':['def'],'fgh':['ijk'] (...)}, 'idb':{'lmn':['opq'],'rst':['uvw']} (...)}
Thank you!!
Note: I get this structure because I am using a list/map structure earlier in the code to extract text from a XML file which yields list values.
get_text = lambda x: x.text
content = [list(map(get_text, i)) for i in content]
Upvotes: 2
Views: 319
Reputation: 3048
This works:
dictionary = {'id1':{'key11':['value11'],'key12':['value12']}, 'id2':{'key21':['value21'],'key22':['value22']}}
new_dict = {key: {key1:value1[0] for key1, value1 in value.items()} for key, value in dictionary.items()}
new_dict
#{'id1': {'key11': 'value11', 'key12': 'value12'},
# 'id2': {'key21': 'value21', 'key22': 'value22'}}
Also, I would not use predefined terms like dict
Upvotes: 5