我是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语句吗?
答案 0 :(得分:7)
列表不可清除,因此不能成为字典中的键。
为什么您希望您的密钥成为列表?如果您正在调用函数
expect_iterable_of_lists(d.keys())
,您只需合并map
和list
:
expect_iterable_of_lists(map(list, d.keys()))
答案 1 :(得分:2)
正如其他人所说,将列表用作字典键可能不是一个好主意。
如果这是你真正需要的,那么为列表添加可用性并不困难:
>>> class List(list):
def __hash__(self):
return hash(tuple(self))
>>> d = {("apple", "banana", "pear", "pineapple"):24,
("banana", "pineapple", "apple", "pear"):17,
("pineapple", "pear", "banana", "apple"):10,
("apple", "pineapple", "banana", "pear"):16}
>>> new_d = {List(k):v for k, v in d.items()}
>>> new_d
{['banana', 'pineapple', 'apple', 'pear']: 17,
['apple', 'banana', 'pear', 'pineapple']: 24,
['pineapple', 'pear', 'banana', 'apple']: 10,
['apple', 'pineapple', 'banana', 'pear']: 16}
此代码将实现您使用列表键的目标,只要您不改变列表,它就会正常工作(基于哈希表的dicts不能与可变键一起使用) 。如果你确实需要改变密钥,那么你需要一个不依赖于散列的替代字典实现(例如association list)。