When i tried the following in python interpreter,i got a syntax error:

d = {[[['a': 1,'b': 2],['a': 4,'b': 3]][['a': 2,'c': 2],['a': 1,'c': 3]]] : 0.4}

Pleeeez help :sad:

Dani AI

Generated

A quick, practical follow-up to and with safe, reusable options for using nested lists as dictionary keys.

For a one-off mapping from two equal-length lists, build the dict with zip and convert each list-key to an immutable form on the fly. Example pattern:

d = { tuple(k): v for k, v in zip(list_of_keys, list_of_values) }

For arbitrarily nested lists (lists inside lists, dicts, sets, etc.) convert the whole structure to a canonical immutable form before using it as a key. A common approach is a small recursive "deep freeze" that turns lists -> tuples, sets -> frozensets and dicts -> frozensets of (key,value) pairs, then use the result as the hashable key:

def deep_freeze(obj):
    if isinstance(obj, list):
        return tuple(deep_freeze(x) for x in obj)
    if isinstance(obj, set):
        return frozenset(deep_freeze(x) for x in obj)
    if isinstance(obj, dict):
        return frozenset((deep_freeze(k), deep_freeze(v)) for k, v in obj.items())
    return obj

Use key = deep_freeze(nested_structure) and then mydict[key] = value. Caveats: performance cost for large structures, and bottom-level elements must themselves be hashable after freezing. If a canonical textual form is acceptable, serializing with json.dumps(..., sort_keys=True) or pickle.dumps(...) is another option (watch performance and serialization constraints). To check whether an object can already be used as a key, test isinstance(obj, collections.abc.Hashable) or try hash(obj).

Official references: Python's definition of hashable and dict behavior are documented in the language reference and stdlib docs (see hashable and mapping types — dict).

Recommended Answers

All 3 Replies

Dictionary keys have to be immutable objects. Lists are mutable objects. Comvert all the lists to tuples.

how can i convert a list into a tuple...i know the difference is in the brackets(curly for tuples and square for lists) but how to actually do it for a list of lists?
Basically i have 2 lists of equal length and i want to create a mapping from l1 to l2. So i have to use dictionary.Any ideas on how to do this?
EDIT:sorry for this...i should have googled a bit :)

Here is a possible way to create tuples from lists:

list1 = [1, 2, 3]
tuple1 = tuple(list1)

print list1   # [1, 2, 3]
print tuple1  # (1, 2, 3)

list2 = [[1, 2], [3, 4]]
tuple2 = tuple([tuple(sublist) for sublist in list2])

print list2   # [[1, 2], [3, 4]]
print tuple2  # ((1, 2), (3, 4))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.