简体   繁体   中英

How can I map two elements of a tuple to each other using a dictionary in Python?

Let's say I have a tuple that has the two elements

(a, b)

How can I create a dictionary that maps the first element to the second so it looks like

{a : b}

I have tried

new_dict = {tup[0]:tup[1]}

but I receive a

TypeError: unhashable type 'list'

The error you're receiving means your key a is a list, which can't be used as a key. Something like this

(['item'], 'value')

When what you probably want is

('key', 'value')

Typically, dictionary keys are strings, though not strictly so. They can also be integers or other immutable types. "Immutable" means it can't be updated in place. A list can be updated in place by adding or removing an item, so it can't be properly hashed and, subsequently, can't be used as a key.

Your error message suggests that the first item of your tuple is a list. Lists are mutable and therefore can't be dictionary keys, but tuples can. So, convert the would-be key from list to tuple:

new_dict = { tuple(tup[0]), tup[1] }

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