gpt4 book ai didi

python - 如何将元组字典转换为列表字典(Python)?

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:25 25 4
gpt4 key购买 nike

我是 Python(和一般编程)的新手,但我有一个字典,其中的键是元组,我想用与列表相同的键创建一个新字典。

我的意思是:

我有:

d = {("apple", "banana", "pear", "pineapple"):24, 
("banana", "pineapple", "apple", "pear"):17,
("pineapple", "pear", "banana", "apple"):10,
("apple", "pineapple", "banana", "pear"):16}

我要:

new_d = {["apple", "banana", "pear", "pineapple"]:24, 
["banana", "pineapple", "apple", "pear"]:17,
["pineapple", "pear", "banana", "apple"]:10,
["apple", "pineapple", "banana", "pear"]:16}

是否有使用 for 循环和 if 语句的简单方法来做到这一点?

最佳答案

列表不可散列,因此不能作为字典中的键。

为什么你希望你的键是列表?如果您当前正在调用一个函数

expect_iterable_of_lists(d.keys())

,你可以简单地组合maplist:

expect_iterable_of_lists(map(list, d.keys()))

关于python - 如何将元组字典转换为列表字典(Python)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13672639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com