tuple_list_dictionary整理中...

本文介绍了如何在Python中操作字典类型,包括创建、遍历及将字符串转换为字典的方法。通过示例展示了使用ast.literal_eval进行安全的字符串到字典的转换,以及利用json.loads解析JSON格式字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本特点

tuple

==

list

==

dictionary

==

遍历

tuple

==

list

==

dictionary

==

转换

str==>dictionary

使用ast

MAC OSX 10.9.2
>>> en = "China".decode('utf8')
>>> cn = "中国".decode('utf8')
>>> print en
China
>>> print cn
中国
>>> s1 = {'en': en, 'cn': cn}
>>> print s1
{'en': u'China', 'cn': u'\u4e2d\u56fd'}
>>> s2 = "{'en': u'China', 'cn': u'\\u4e2d\\u56fd'}"
>>> ast.literal_eval(s2)
{'en': u'China', 'cn': u'\u4e2d\u56fd'}
>>> print ast.literal_eval(s2) #把字符串s2转换成dictionary
{'en': u'China', 'cn': u'\u4e2d\u56fd'}

json string ==> dictionary

使用json.loads 要求字符串符合 json格式

1

Windows7
>>> ss1 = '[{"name":"sam","cn":"山姆"}]'
>>> json.loads(ss1)
[{u'name': u'sam', u'cn': u'\u027d\u0137'}]

2

Windows7
>>> ss = '{"one": null,"two":{"a": "1", "b": null, "c": "西"}, "three": "3"}'
>>>
>>> sj = json.loads(ss.decode('gbk'))
>>> print sj
{u'three': u'3', u'two': {u'a': u'1', u'c': u'\u897f', u'b': None}, u'one': None
}
>>> sj["two"]["c"]
u'\u897f'
>>> print sj["two"]["c"]
西
>>>
3
Windows7
>>> ss = '[{"one": null,"two":{"a": "1", "b": null, "c": "西"}, "three": "3"}, {
"oo": "欧", "tt": "22"}]'
>>> sj = json.loads(ss.decode('gbk'))
>>> sj[1]["oo"]
u'\u6b27'
>>> print sj[1]["oo"]
欧
>>>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值