Skip to content
Advertisement

How to remove array from values in a dictionary

I have the following dictionary

{"contact_uuid": ["67460e74-02e3-11e8-b443-00163e990bdb"], "choices": ["None"], "value": [""], "cardType": [""], "step": ["None"], "optionId": ["None"], "path": [""], "title": [""], "description": [""], "message": [""]}

But I’d like to remove the lists so it looks like this:

{'contact_uuid': '67460e74-02e3-11e8-b443-00163e990bdb', 'choices': "None", "value": "", 'cardType': "", 'step': 'None', 'optionId': 'None', 'path': '', 'title': "", 'description': "", 'message': ""}

Is there a simple way to do this? I think I might be able to iterate through and remove the list. Thanks

Advertisement

Answer

In order to produce the required output you will need a list (set) of keys that should not be modified. Something like this:

dict_ = {
    "contact_uuid": ["67460e74-02e3-11e8-b443-00163e990bdb"],
    "choices": ["None"],
    "value": [""],
    "cardType": [""],
    "step": ["None"],
    "optionId": ["None"],
    "path": [""],
    "title": [""],
    "description": [""],
    "message": [""]
}

for k, v in dict_.items():
    if isinstance(v, list) and k not in {'value', 'cardType', 'step', 'optionId', 'path'}:
        dict_[k] = v[0]

print(dict_)

Output:

{'contact_uuid': '67460e74-02e3-11e8-b443-00163e990bdb', 'choices': 'None', 'value': [''], 'cardType': [''], 'step': ['None'], 'optionId': ['None'], 'path': [''], 'title': '', 'description': '', 'message': ''}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement