简体   繁体   English

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

[英]How to convert a dictionary of tuples into a dictionary of lists (Python)?

I'm new to Python (and programming in general), but I have a dictionary with the keys being tuples, and I want to make a new dictionary with those same keys as lists. 我是Python的新手(并且是一般编程人员),但是我有一个字典,键为元组,并且我想用与列表相同的键创建一个新的字典。

here's what I mean: 这是我的意思:

I have: 我有:

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

I want: 我想要:

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

is there a simple way to do this using for loops and if statements? 有没有一种简单的方法使用for循环和if语句来做到这一点?

lists are not hashable and therefore cannot be keys in a dictionary. 列表不可散列,因此不能是字典中的键。

Why do you want your keys to be lists? 为什么要让您的钥匙成为清单? If you're currently calling a function 如果您当前正在调用一个函数

expect_iterable_of_lists(d.keys())

, you can simply combine map and list : ,您只需将maplist组合即可:

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

As noted by others, it likely isn't a good idea to use lists as dictionary keys. 正如其他人所指出的那样,将列表用作字典键可能不是一个好主意。

If that is what you really need though, it isn't hard to add hashability to lists: 如果这是您真正需要的,则不难在列表中添加哈希值:

>>> 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}

This code will achieve your goal of using a list a key and it will work just fine as long as you don't mutate the list (dicts based on hash tables don't work well with mutable keys). 该代码将实现您使用列表键的目标,并且只要您不对列表进行突变(基于哈希表的指令不适用于可变键),它就可以正常工作。 If you do need to mutate the keys, you'll need an alternative dictionary implementation that doesn't rely on hashing (an association list for example). 如果确实需要更改键,则需要一个不依赖散列的替代字典实现(例如, 关联列表 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM