擅长:python、mysql、java
<p>这是<a href="https://stackoverflow.com/a/14902564/832230">answer by jfs</a>的linter固定和类型注释版本。解决了各种绒布突出的问题。Python 3.6+使用f-strings也使其现代化。</p>
<pre><code>import json
from typing import Any, Dict, Hashable, List, Tuple
def check_for_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: Dict = {}
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=check_for_duplicate_keys)
</code></pre>