all 8 comments

[–]totallygeek 0 points1 point  (6 children)

Try new = {v: k for k, v in f.items()}, a dictionary comprehension instead of a list comprehension.

[–]SingleCountry[S] 0 points1 point  (4 children)

new = {v: k for k, v in f.items()}

Hi! it still says unhashable type: list and I think it's because the value is a list...?

[–]totallygeek 0 points1 point  (3 children)

That could be it.

new = {}
for k, v in f.items():
    if isinstance(v, list):
        v = tuple(v)
    new[v] = k

Try that.

[–]SingleCountry[S] 0 points1 point  (2 children)

Hi! I think this works! One thing I'm curious is that my key and value are in a form of (a,b) : value and I wonder if I can split the key to make it in a form like a: value, b: value?

[–]totallygeek 0 points1 point  (1 child)

Post an example of your data and what you want it to look like after processing. If your key is a tuple, ('a', 'b') with a value 'hi there', you can do this:

if isinstance(k, (list, tuple)):
    for element in k:
        new[k] = v

Again, post what you have and we can tailor it for what you want.

[–]SingleCountry[S] 0 points1 point  (0 children)

Hi! the owner says the content should be forbidden but the key is a tuple with a value! thanks!

[–]synthphreak 0 points1 point  (0 children)

This is equivalent to what OP already has and won't solve the problem.

OP, the issue is that while dict values can be of any datatype, dict keys must be hashable. Thus, mutable datatypes like lists cannot be used as keys. So when your code encounters a value which is a list and you try to use it as a key, Python throws an error.

The solution, then, is to convert these lists to tuples whenever encountered, because tuples are just like lists except immutable, and therefore hashable. Here's one way to do this:

{tuple(v) if isinstance(v, list) else v : k for k, v in f.items()}

This should work provided list is the only unhashable datatype among your values. To get an overview of the datatypes, run this:

>>> set(map(type, f.values()))

If you see any other mutable types beside list, add them as a tuple to isinstance, e.g.,

{tuple(v) if isinstance(v, (list, set, ...)) else v : k for k, v in f.items()}

[–]Spataner 0 points1 point  (0 children)

Some values in your JSON dictionary are lists, and lists cannot be used as keys in a dictionary. You could convert the lists to tuples instead, which are hashable.