Issue
how would I convert the following nested dictionary to a single dictionary
status = {'data': {'isFault': False, 'isButton': False, 'battery': 'NORMAL', 'powerInput': 'NOT_PRESENT', 'powerInput5vIo': 'NOT_PRESENT'}, 'error': 'NO_ERROR'}
I want it to look like this:
new_status = {'isFault': False, 'isButton': False, 'battery': 'NORMAL', 'powerInput': 'NOT_PRESENT', 'powerInput5vIo': 'NOT_PRESENT', 'error': 'NO_ERROR'}
for k, v in status['data'].items():
print (k, ":", v)
I managed to extract the key, value pairs from 'data' but I'm stuck.
Solution
Do you need to preserve the inner dictionary or are you free to mutate it. If the latter, just extract it and use it as a base adding in the missing members:
inner = status['data']
del status['data']
inner.update(**status)
result = inner
Note, if any keys occur in both the inner and outer dict, the outer overwrites the inner key with the code above. If you need to not modify it in-place, just copy it first:
from copy import copy
temp = copy(status)
inner = temp['data']
del temp['data']
inner.update(**temp)
result = inner
And finally, if inner should take precedence over outer, then reverse the last statement:
temp.update(**inner)
result = temp
And you have your result.
Answered By - penguin359
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.