json.loads allows duplicate keys in a dictionary, overwriting the first value

前端 未结 4 1625
自闭症患者
自闭症患者 2020-11-27 18:54
>>> raw_post_data = request.raw_post_data
>>> print raw_post_data
{\"group\":{\"groupId\":\"2\", \"groupName\":\"GroupName\"}, \"members\":{\"1\":{         


        
4条回答
  •  误落风尘
    2020-11-27 19:40

    This is a linter-fixed and type-annotated version of the answer by jfs. Issues highlighted by various linters were addressed. It is also modernized for Python 3.6+ to use f-strings.

    import json
    from typing import Any, Dict, Hashable, List, Tuple
    
    def raise_on_duplicate_keys(ordered_pairs: List[Tuple[Hashable, Any]]) -> Dict:
        """Raise ValueError if a duplicate key exists in provided ordered list of pairs, otherwise return a dict."""
        dict_out = {}
        for key, val in ordered_pairs:
            if key in dict_out:
                raise ValueError(f'Duplicate key: {key}')
            else:
                dict_out[key] = val
        return dict_out
    
    json.loads('{"x": 1, "x": 2}', object_pairs_hook=raise_on_duplicate_keys)
    

    ordered_pairs above is a list of tuples, with each tuple having a key and a value. Refer to the docs for object_pairs_hook.

提交回复
热议问题