why I cannot write this {names: heroes} inside the dictionary .when I did this
{{names: heroes} for names, heroes in zip(names, heroes)} an error occurred which is a type error saying unhashable dict. What does that mean?
nums={{names:heroes} for names, heroes in zip(names,heroes)}
print(nums)
Traceback (most recent call last):
File "C:/Users/ahmod/AppData/Local/Programs/Python/Python37-32/mim.py", line 7, in <module>
nums={{names:heroes} for names, heroes in zip(names,heroes)}
File "C:/Users/ahmod/AppData/Local/Programs/Python/Python37-32/mim.py", line 7, in <setcomp>
nums={{names:heroes} for names, heroes in zip(names,heroes)}
TypeError: unhashable type: 'dict'
{{names: heroes} for names, heroes in zip(names, heroes)}
This is a set comprehension -because you are using the {} curly braces. In a set, each element must be hashable. you are setting each elements in the set to {names: heroes} - which is a dict. So you are trying to make a set of dict.
But unfortunately, in python, dict is not hashable - since it's a mutable type.
So you can't do that.
Instead you can try to create a dictionary directly:
{name: heroe for name, heroe in zip(names, heroes)}
By just removing the extra curly braces.
Related
I have a 2D list (a list of lists) and am trying to use the notation list[:,colIndex] to pull out a single column's data into another list, but I'm getting a TypeError: list indices must be integers error.
for example:
lst = [[1,2,3],[10,12,13]]
lst[:,0]
Returns:
Traceback (most recent call last):
File "<input>", line 2, in <module>
TypeError: list indices must be integers
I don't understand...
Edit:
Running this in Python 3.9 gives me:
TypeError: list indices must be integers or slices, not tuple
It would seem that the [:,colIndex] syntax isn't supported by lists and is available to numpy arrays only :(
However I can use: list(zip(*lst))[colIndex] instead from this answer https://stackoverflow.com/a/44360278/1733467
In a python defaultdict object (like obj1), I can call obj1['hello','there'] and get item. but when the input list is variable (for example: input_list), how I can call obj1[input_list]?
when I call obj1[input_list], python raise this error:
TypeError: unhashable type: 'list'
when use obj1[*input_list], python returns:
SyntaxError: invalid syntax
So what is the correct way to put list as variable in defaultdict?
The error TypeError: unhashable type: 'list' states that list is not hashable, but a dict always needs a hashable key!
If you test my_normal_dict[2,3] you can see that it actually treats these two numbers as the tuple (2,3) because the error is KeyError: (2, 3), so you need to input a hashable iterable like a tuple.
For example, my_dict[tuple(my_list)] should work, as long as all the elements of the tuple itself are hashable!
Note though: If your list is large, it may be relevant that this needs to copy all elements into a tuple.
I get this error after running a program:
Traceback (most recent call last):
File "J:#", line 21, in <module>
data = {name: {user_details}}
TypeError: unhashable type: 'dict'
So as far as I understood, we cannot use dictionary as a key in a dict "key : value" relationship.
This is the part of the code causing the issue on line 21:
data = {name: {user_details}}
Could you please explain to me how do I actually fix it. Been on internet a day or so, could not understand =( Thank you in advance bros and sis
Hashable data types: int, float, str, tuple, and NoneType.
Unhashable data types: dict, list, and set.
Just use hashable data types as keys
Can the return in an If statement append a list?
Is python aware that the list elements are actually dictionaries and that 'sublist' iterates over those elements?
I tried being data type specific after For previously and that doesn't help
Is the If statement actually accessing the dictionary?
My code:
In[1]: restaurants = [fork_fig, frontier_restaurant]
In [2]: def open_restaurants(restaurants):
for sublsit in restaurants:
op=[]
if sublist.get('is_closed')==False:
op.append(sublist.get('name'))
passed through their code:
In [1]: len(open_restaurants(restaurants))
Out[2]: NameErrorTraceback (most recent call last)
<ipython-input-14-e78afc732a29> in <module>
----> 1 len(open_restaurants(restaurants)) # 1
<ipython-input-13-56ad484d6dd9> in open_restaurants(restaurants)
2 for sublsit in restaurants:
3 op=[]
----> 4 if sublist.get('is_closed')==False:
5 op.append(sublist.get('name'))
6
NameError: name 'sublist' is not defined
and next: I think this is because the list i defined is not populating with the correct information.
In[3]: open_restaurants(restaurants)[0]['name'] # 'Fork & Fig'
Out[4]:TypeErrorTraceback (most recent call last)
<ipython-input-15-bf5607d088f4> in <module>
----> 1 open_restaurants(restaurants)[0]['name'] # 'Fork & Fig'
TypeError: 'NoneType' object is not subscriptable
Your indentation may be not correct
You didn't return the result (probably return op) in your function
The problem here was that I was entering too much information.
The code that ended up working perfectly was as follows:
def open_restaurants(restaurants):
op=[]
for sublist in restaurants:
if sublist['is_closed']==False:
op.append(sublist)
return op
I separated op list from the for loop.
Previously, the NameError said sublist was not defined, yet it was
defined by including it in the For; to fix I removed .get() and
replaced it with list form x[].
Last, separated return from the .append() function.
I am trying to use a set literal {} to create a set from a list,
fields = ['field1', 'field2', 'field3', 'field4']
{fields}
TypeError: unhashable type: 'list'
had to use set(fields) to create a set,
{'field1', 'field2', 'field3', 'field4'}
I am wondering what is the reason behind this behavior.
Literals are not used to convert; the following won't convert a set to a list either:
aset = {'foo', 'bar'}
alist_from_aset = [aset]
That'd create a list with one element, the set. Your attempt tells Python to create a set with one element, but sets only take hashable objects, and a list is not such an object.
In recent Python 3 releases, you can use iterable unpacking to expand values into separate elements:
{*fields}
That unpacks all the values from a variable into separate values for a set literal:
>>> fields = ['field1', 'field2', 'field3', 'field4']
>>> {*fields}
{'field2', 'field3', 'field1', 'field4'}
See PEP 448 -- Additional Unpacking Generalizations; it's new in Python 3.5.
With {fields} you're trying to make a new set with fields as an element, but list is not hashable, so Python complaints.
set works another way, it expects iterables:
>>> set(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> set('field1')
set(['e', 'd', 'f', 'i', 'l', '1'])
You can create a new set of fields values this way:
>>> fields = ['field1', 'field2', 'field3', 'field4', 'field1']
>>> {*fields}
{'field1', 'field3', 'field4', 'field2'}
Note that you can't create an empty set with {} (that gives you a dict), you have to rely on set() in that cases.