Why Can't I Use a List as a Dict Key in Python

Why can't I use a list as a dict key in python?

There's a good article on the topic in the Python wiki: Why Lists Can't Be Dictionary Keys. As explained there:

What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?

It can be done without really breaking any of the requirements, but it leads to unexpected behavior. Lists are generally treated as if their value was derived from their content's values, for instance when checking (in-)equality. Many would - understandably - expect that you can use any list [1, 2] to get the same key, where you'd have to keep around exactly the same list object. But lookup by value breaks as soon as a list used as key is modified, and for lookup by identity requires you to keep around exactly the same list - which isn't requires for any other common list operation (at least none I can think of).

Other objects such as modules and object make a much bigger deal out of their object identity anyway (when was the last time you had two distinct module objects called sys?), and are compared by that anyway. Therefore, it's less surprising - or even expected - that they, when used as dict keys, compare by identity in that case as well.

Why can lists not be used as dictionary keys?

You can use a tuple as a dictionary key instead:

data = { 
(24,48,96): ["QN.FN.EQ", "OT.AR.LN", "BL.VL.TR"]
}

print data[(24,48,96)]

How to insert a list as a key in Python dictionary

You can't, a list is mutable and therefore non-hashable. Dictionary keys need to be hashable.

What you can do is use a tuple instead.

d= { ('a','b','c'): 1 }

Use a list as the key in a Python dict

Since your lists have complex elements (tuple of list of tuples of strings), they have to be converted to contain tuples of tuples of strings so they are hashable. Like this:

list1a = [ tuple(x) for x in list1 ]
list2a = [ tuple(x) for x in list2 ]

print borda_sort([list1a, list2a])

# prints [(('diritti', 'S'), ('umani', 'A')), (('forze', 'S'), ('di', 'E'), ('sicurezza', 'S')), (('violazioni', 'S'), ('dei', 'E'), ('diritti', 'S'), ('umani', 'A')), (('anni', 'S'), ('di', 'E'), ('carcere', 'S')), (('violazioni', 'S'), ('dei', 'E'), ('diritti', 'S')), (('Nazioni', 'SP'), ('Unite', 'SP')), (('uso', 'S'), ('eccessivo', 'A'), ('della', 'E'), ('forza', 'S'))]

OLD ANSWER If you have list1 and list2, the way to call this function is borda_sort([list1, list2]) (or borda_sort((list1, list2)), either works the same). If your lists contain individual elements in the same order that you want to use for borda, the answer is to make a list of lists, not to zip your lists together. I think zip() doesn't do what you think it does. zip makes a list of pairs from a pair of lists, like this:

>>> zip((1, 2, 3), ('a', 'b', 'c'))
[(1, 'a'), (2, 'b'), (3, 'c')]

Create a dictonary with a list as key

A dictionary key must be immutable (https://realpython.com/lessons/restrictions-dictionary-keys-and-values/), and a list is a mutable object.

In the for loop, you can append tuples instead of lists, as they're immutable

for j in range(0, len(w), 2):
l2 = list((w[j], w[j+1]))
for i in psu:
if w[j] == i or w[j+1] == i:
pass
else:
m = ('_'.join(l2))
r.append((m, i))
Pre = dict(zip(r, Pre_arr))

Can I get lists as keys in a dictionary?

not sure if this works for you but you could just convert the list to a string, so that you can use it as a key in the dictionary:

trylist = [1,2,3,4]
d = {}
d[str(trylist)] = 'value'
print(d)

but using a tuple should work too:

trylist = (1,2,3,4)
d = {}
d[trylist] = 'value'
print(d)

Error Appending list elements to dictionary in Python

You are providing an empty list, and fromkeys() uses this particular object for all the keys, so that their corresponding values refer to the same object. When you do d['a'].append(10), it appends 10 to this single object, which all the dict items share, thus resulting in what you are getting now.

Python document mentions this exact situation:

fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.

— https://docs.python.org/3/library/stdtypes.html#mapping-types-dict

Following the suggetion in the python doc, you can do d = {k: [] for k in keys} instead.



Related Topics



Leave a reply



Submit