Python 将非str foo添加到dict键
如何将[same]非str foo添加到字典的所有str键,以便Python 将非str foo添加到dict键,python,dictionary,Python,Dictionary,如何将[same]非str foo添加到字典的所有str键,以便 a = {'continent': ['America', 'Africa'], 'country': ['USA', 'Egypt']} 变成: a = {foo(bar='continent', hello=world): ['America', 'Africa'], foo(bar='country', hello=world): ['USA', 'Egypt']} 在这里,我使用字典理解来迭代dicta中的键和值,并应
a = {'continent': ['America', 'Africa'], 'country': ['USA', 'Egypt']}
变成:
a = {foo(bar='continent', hello=world): ['America', 'Africa'], foo(bar='country', hello=world): ['USA', 'Egypt']}
在这里,我使用字典理解来迭代dict
a
中的键和值,并应用函数foo
定义的任何转换:
def foo(bar, hello):
return bar + hello # or whatever you want to do
a = {'continent': ['America', 'Africa'], 'country': ['USA', 'Egypt']}
b = {foo(bar=k, hello='world'): v for k,v in a.items()}
打印b
产生:
{'continentworld': ['America', 'Africa'], 'countryworld': ['USA', 'Egypt']}
在Python中,不必使用字符串作为字典键。字典键的唯一要求是它们是可散列的对象
从:
要用作字典键,对象必须支持哈希函数(例如,通过\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
)、相等比较(例如,通过\uuuuuuueq\uuuuuuuuuuu
)
非str foo所代表的是
foo
一个函数?foo看起来像一个命名的元组…?函数可以用作字典中的键,因为所有对象的比较都只等于它们自己,除非覆盖了\uuuuuuueq\uuuuu
或\uuuuucmp\uuuuu
。@ppperry很棒的一点-在添加代码段之前,我刚刚检查了函数上的\uuuuuueq\uuuuuuuu>和\uucmp\ucode>,发现它们不可用并进行了编辑。现在删除它,谢谢你教我一些新的东西。此外,python中的\uuuu cmp\uuuu
魔术方法也被删除了3@chucksmash-我正在尝试获取非str密钥