简体   繁体   English

在python中定义字典获取TypeError:unhashable类型:'dict'

[英]defining dictionary in python getting TypeError: unhashable type: 'dict'

i am trying to create a dictionary like something below:我正在尝试创建一个像下面这样的字典:

frnd_detail1 = {
    {'name':'AD', 'age': 30}, {'name':'AKB', 'age':90},  {'name':'SD', 'age':40}
}

but i am getting the below error message as:但我收到以下错误消息:

File "<ipython-input-72-a0d88fef112d>", line 4, in <module>
    {'name':'SD', 'age':40}

TypeError: unhashable type: 'dict'

why it is so, please provide some details为什么会这样,请提供一些详细信息

You are creating a set (by accident I guess) by surrounding your dictionaries with curly braces {} .您正在通过用大括号{}包围您的字典来创建一个集合(我猜是偶然的)。

In Python you can create sets using {} like this:在 Python 中,您可以使用{}创建集合,如下所示:

>>> my_set = {1,2,3}
>>> print(type(my_set))
<type 'set'>

Sets can only have values that are hashable.集合只能具有可散列的值。 A dict isn't hashable which is why you get the error. dict不可散列,这就是您收到错误的原因。 You might want to create a list instead by replacing your outer {} with [] like this:您可能希望通过将外部{}替换为[]来创建一个list ,如下所示:

frnd_detail1 = [{'name': 'AD', 'age': 30}, {'name': 'AKB', 'age': 90}, {'name': 'SD', 'age': 40}]

I guess you want to create a dictionary of dictionaries or list of dictionaries.我猜您想创建字典字典或字典列表。

If its a dict of dicts, then you need to give a key for its value, and not just ut each dictionary independently.如果它是 dicts 的 dict,那么您需要为其值提供一个键,而不仅仅是 ut 每个字典独立。

If its a list of dicts, you can append each dict into a list.如果它是一个字典列表,您可以将每个字典附加到一个列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM