简体   繁体   中英

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.

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?

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 :

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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