为什么不能用dict()函数将str数据转换成字典类型

为什么不能用dict()函数将str数据转换成字典类型

        这问题很蠢哈,但是以前最开始接触python的时候,正好接触了python的很多数据类型转换的知识点,对于python极为便捷的数据类型互相转换,那是叹为观止。
        但是好巧不巧的,实际上最常用的反而是json格式的数据,因此经常要和dict 类型的数据打交道。
        由于思维惯性,最常犯的错误就是“str()能直接转字符串,那dict()就能转字典”,真的就像着魔似的,总是往这错的地方想,最后为了避免总犯低级错误,还是认真了解了一下为啥dict() 不能用于str数据类型转换。

#我们先重现一下自己犯的错误
#将一个自定义的字符串,通过dict()函数直接转dict
json_str=r'{"key":"valuea"}'
new_json=dict(json_str)
print(new_json)
#执行会看到报错
#>>>new_json=dict(json_str)
#>>>ValueError: dictionary update sequence element #0 has length 1; 2 is required

# 为什么会报错?其实翻看具体的函数信息,就能看到这个函数注释给我们的答案
# 因为dict() 表示建立一个空的字典数据
# dict(mapping)  通过一个mapping对象进行初始化,新建一个字典
# dict={}
# for k,v in iterable:
#       dict[k]=v
# iterable 表示可迭代对象,也就是可以循环获取数据的对象
# csv 文件、另一个字典、一个list里的多个数据、一个元组里的多个元素,这些都是天然的可迭代对象
'''
def __init__(self, seq=None, **kwargs):  # known special case of dict.__init__
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    # (copied from class doc)
    """
'''
pass

简单了解dict 数据类型

#dict是一种键值对的格式,在有些程序里也叫map,例如JavaScript
#当然,如果说另一种格式,会更熟悉:json
{
	"key":"123",
	"key2":"abc"
}
#dict() 对key的要求是:key 必须是一种不可变的数据类型。
#python中,“不可变”的数据类型包括:string、int

dict字典到底怎么赋值?

dict的赋值方式有三种:
#1、通过初始化固定dict的key-value
test_dict={"key":"123456"}

#2、通过指定key将数据放入dict
#由于一个key只能放入一个value,所以如果重复,则会将此前的数据冲掉。
test_dict={}
test_dict["test1"]="1"
#此时字典的key和value会同时存入字典

#3、通过读取具备成对关系的csv文件,文件中只有两列数据
#设file_name='data.csv'
file=open(file_name,'r')
table=csv.reader(file)
dic=dict(table)
#此时print(dic)就会发现,已经获得一个完美的json串,或者说字典数据了

那遇到str类型的json数据,要怎么传?

json_str=r'{"key":"valuea"}'
new_json=eval(json_str)
print(new_json)
#···> 此时,我们会看到数据以我们想要的dict字典格式,展现了
{'key': 'valuea'}

关于eval() 函数

def eval(*args, **kwargs): # real signature unknown
    """
    Evaluate the given source in the context of globals and locals.
    
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
    """
    pass
虽然我们并不是特别明白,所说的“任何映射”具体是指什么
但是全局变量,必须是字典格式
The globals must be a dictionary
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值