方法
使用集合交集计算共享密钥。
2.7 之前的代码
def convert(items, ID):
# Find the shared keys
dst, src = set(items.keys()), set(ID.keys())
same_keys, diff_keys = dst.intersection(src), dst.difference(src)
# Make a new dictionary using the shared keys
new_values = [(ID[key], items[key]) for key in same_keys]
old_values = [(key, items[key]) for key in diff_keys]
return dict(new_values + old_values)
2.7+ 的代码
def convert(items, ID):
# Find the shared keys
dst, src = set(items.keys()), set(ID.keys())
same_keys, diff_keys = dst.intersection(src), dst.difference(src)
# Make a new dictionary using the shared keys
new_values = {ID[key]: items[key] for key in same_keys}
old_values = {key: items[key] for key in diff_keys}
return reduce(lambda dst, src: dst.update(src) or dst, [new_values, old_values], {})
2.7 之前的测试
>>> def convert(items, ID):
... # Find the shared keys
... dst, src = set(items.keys()), set(ID.keys())
... same_keys, diff_keys = dst.intersection(src), dst.difference(src)
... # Make a new dictionary using the shared keys
... new_values = [(ID[key], items[key]) for key in same_keys]
... old_values = [(key, items[key]) for key in diff_keys]
... return dict(new_values + old_values)
...
>>> convert({"apple" : 42, "pear": 38}, {"apple" : "Apples", "peach": 31})
{'pear': 38, 'Apples': 42}
测试 2.7+
>>> def convert(items, ID):
... # Find the shared keys
... dst, src = set(items.keys()), set(ID.keys())
... same_keys, diff_keys = dst.intersection(src), dst.difference(src)
... # Make a new dictionary using the shared keys
... new_values = {ID[key]: items[key] for key in same_keys}
... old_values = {key: items[key] for key in diff_keys}
... return reduce(lambda dst, src: dst.update(src) or dst, [new_values, old_values], {})
...
>>> convert({"apple" : 42, "pear": 38}, {"apple" : "Apples", "peach": 31})
{'pear': 38, 'Apples': 42}