Home > database >  Python - How to unpack key with key,value pair?
Python - How to unpack key with key,value pair?

Time:02-13

Anyone can help and explain how to unpack items from key with many key,value pair?

{'jsonrpc': '2.0', 'result': [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}], 'id': '1'}

I need transform 'result' to dictionary.

# Print type 'dict'
print(type(result2))

#Print type 'list'
print(type(result2['result']))

output = []


# Here i get error 

for key_value in result2['result']:
    key, value = key_value.split(': ', 1)
    if not output or key in output[-1]:
        output.append({})
    output[-1][key] = value

print(output)

"""
    key, value = key_value.split(': ', 1)
AttributeError: 'dict' object has no attribute 'split'
"""

Thank you in advance

CodePudding user response:

As clearly result2['result'] is a list but that list contains the dict which you want.

So to get that simply unpack this list and get the frst element;

result2['result'][0]

CodePudding user response:

result2['result'] is a list of dicts. To iterate over the list, you can do for result in result2['result'] To iterate over each resulting dict, you can do for key, value in result.items().

result2 = {'jsonrpc': '2.0', 'result': [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}], 'id': '1'}

output = [{}]
for result in result2['result']:
    for key, value in result.items():
        if key in output[-1]:
            output.append({})
        output[-1][key] = value

print(output)
# [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}]

This code goes to a lot of trouble to iterate through each dictionary and accumulate a list of new dictionaries for the apparent purpose of combining dictionaries with disjoint sets of keys, but for this particular input, or any other input where each dictionary in result has the same keys, or any input where there's only one dictionary, there's no point in iterating over the dictionaries at all. You could just as easily do:

output = result2['result']
print(output)
# [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}]

to get the same exact output with none of the work.

  • Related