python中list,str,json,dict使用

来源:互联网 发布:网络管理平台 编辑:程序博客网 时间:2024/05/07 07:01

Python中使用json.loads解码字符串时出错:ValueError: Expecting property name: line 1 column 2 (char 1)

问题描述

今天在解析字符串中,使用json.loads解码字符串,脚本如下:

import jsonstring = "{u'lat': 61.190495, u'lng': -149.86884}"dic = json.loads(string)
  • 1
  • 2
  • 3
  • 4

运行后报错信息如下:

Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads    return _default_decoder.decode(s)  File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode    obj, end = self.raw_decode(s, idx=_w(s, 0).end())  File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode    obj, end = self._scanner.iterscan(s, **kw).next()  File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan    rval, next_pos = action(m, context)  File "/usr/lib64/python2.6/json/decoder.py", line 171, in JSONObject    raise ValueError(errmsg("Expecting property name", s, end))ValueError: Expecting property name: line 1 column 1 (char 1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

解决方案

1. 替换单引号

类型的错误,就是由于JSON中,标准语法中,不支持单引号,属性或者属性值,都必须是双引号括起来的。

string = string.replace("'", '"')dic = json.loads(string)
  • 1
  • 2

依旧报同样的错误信息,如下:

Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads    return _default_decoder.decode(s)  File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode    obj, end = self.raw_decode(s, idx=_w(s, 0).end())  File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode    obj, end = self._scanner.iterscan(s, **kw).next()  File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan    rval, next_pos = action(m, context)  File "/usr/lib64/python2.6/json/decoder.py", line 171, in JSONObject    raise ValueError(errmsg("Expecting property name", s, end))ValueError: Expecting property name: line 1 column 1 (char 1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2. 替换引号前的u为空,

即去除引号前的u。这种解决编码问题,简单粗暴了点,至于其深入分析,未完待绪。同时也希望各位大神能够提供更好的解决办法。

string = string.replace("u", "") # 这里比较简单,实际中需要用正则条件替换string = string.replace("'", '"')dic = json.loads(string)


simplejson.loads() 有一个手册上没有提及的参数“strict”,这其实是 JSONDecoder 的一个构造参数,即不严格检查JSON语法。

因此,兼容非标准格式的方法即:

[plain] view plain copy
  1. simplejson.loads(json, strict=False)  

1.定义数组

#dingyishuzumoney = []print len(money)  #changduwei0
  • 1
  • 2
  • 3

2.往数组中插入元素

money = []money.append("张总")money.append("王总")money.append("李总")money.append("刘经理")money.append("保洁大妈")money.append("程序员的我")print len(money)    #6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

注意如果执行报SyntaxError: Non-ASCII character '\xe5' in file...,那么需要在文件头部写上

#coding:utf-8
  • 1

3.打印数组里的某个元素

#打印出素组中某个元素print money[4]  #保洁大妈
  • 1
  • 2

4.遍历数组(注意for后面的冒号)

money = ["张总","王总","李总","刘经理","保洁大妈","程序员的我"]for m in money:    print m
  • 1
  • 2
  • 3
  • 4

5.数组索引范围

money = ["张总","王总","李总","刘经理","保洁大妈","程序员的我"]for index in range(1,len(money)):    print money[index]"""王总李总刘经理保洁大妈程序员的我"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

range(1,len(money) 索引范围

6.删除某个元素

money = ["张总","王总","李总","刘经理","保洁大妈","程序员的我"]del money[3]print len(money)    #此时数组里只有5个元素了
  • 1
  • 2
  • 3

7.删除某一个索引范围内的数组元素

money = ["张总","王总","李总","刘经理","保洁大妈","程序员的我"]del money[3:5]  #删除索引3-5,不包含5print len(money)    #4#删除了数组理的 "刘经理","保洁大妈"

1


1

>>> user = "{'name' : 'jim', 'sex' : 'male', 'age': 18}">>> type(user)<type 'str'>>>> b=eval(user)>>> >>> b{'age': 18, 'name': 'jim', 'sex': 'male'}>>> type(b)<type 'dict'>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

关于eval()的说法,官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果。 

另一种专业的转换工具是json

>>> user  = '{"name":"jim","sex":"male","age":"18"}'>>> json.loads(user){u'age': u'18', u'name': u'jim', u'sex': u'male'}>>> type(user)<type 'str'>>>> type(json.loads(user))<type 'dict'>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8


Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。
一、创建字典
字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:

复制代码代码如下:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

也可如此创建字典:
复制代码代码如下:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

注意:
每个键与值用冒号隔开(:),每对用逗号,每对用逗号分割,整体放在花括号中({})。
键必须独一无二,但值则不必。
值可以取任何数据类型,但必须是不可变的,如字符串,数或元组。
二、访问字典里的值
把相应的键放入熟悉的方括弧,如下实例:
复制代码代码如下:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
#以上实例输出结果:

#dict['Name']:  Zara
#dict['Age']:  7


如果用字典里没有的键访问数据,会输出错误如下:
复制代码代码如下:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Alice']: ", dict['Alice'];

#以上实例输出结果:

#dict['Zara']:
#Traceback (most recent call last):
#  File "test.py", line 4, in <module>
#    print "dict['Alice']: ", dict['Alice'];
#KeyError: 'Alice'[/code]
三、修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

复制代码代码如下:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

 
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
#以上实例输出结果:
#dict['Age']:  8
#dict['School']:  DPS School

四、删除字典元素
能删单一的元素也能清空字典,清空只需一项操作。
显示删除一个字典用del命令,如下实例:
复制代码代码如下:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

del dict['Name']; # 删除键是'Name'的条目
dict.clear();     # 清空词典所有条目
del dict ;        # 删除词典

print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
#但这会引发一个异常,因为用del后字典不再存在:

dict['Age']:
#Traceback (most recent call last):
#  File "test.py", line 8, in <module>
#    print "dict['Age']: ", dict['Age'];
#TypeError: 'type' object is unsubscriptable


五、字典键的特性
字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。
两个重要的点需要记住:
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:
复制代码代码如下:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};

print "dict['Name']: ", dict['Name'];
#以上实例输出结果:
#dict['Name']:  Manni

2)键必须不可变,所以可以用数,字符串或元组充当,所以用列表就不行,如下实例:
复制代码代码如下:
#!/usr/bin/python

dict = {['Name']: 'Zara', 'Age': 7};

print "dict['Name']: ", dict['Name'];
#以上实例输出结果:

#Traceback (most recent call last):
#  File "test.py", line 3, in <module>
#    dict = {['Name']: 'Zara', 'Age': 7};
#TypeError: list objects are unhashable


六、字典内置函数&方法
Python字典包含了以下内置函数:
1、cmp(dict1, dict2):比较两个字典元素。
2、len(dict):计算字典元素个数,即键的总数。
3、str(dict):输出字典可打印的字符串表示。
4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。

Python字典包含了以下内置方法:
1、radiansdict.clear():删除字典内所有元素
2、radiansdict.copy():返回一个字典的浅复制
3、radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4、radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值
5、radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false
6、radiansdict.items():以列表返回可遍历的(键, 值) 元组数组
7、radiansdict.keys():以列表返回一个字典所有的键
8、radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
9、radiansdict.update(dict2):把字典dict2的键/值对更新到dict里
10、radiansdict.values():以列表返回字典中的所有值




try:
    x = 100
     y = 200
except IndentationError:
    print('IndentationError: unexpected indent')


# 单行注释
'''
多行注释
多行注释
'''


# 多行代码
str = 'abcd' \
          'efgh'
print(str)


# 多行字符串
str = 'Hello\nworld'
print(str)
str = """Hello
world"""
print(str)

# -*- coding: utf-8 -*-


import string


# 基本类型
print(type(None))
print(type(True))
print(type(12345))
print(type(123.45))
print(type(1234.))
print(type('abc'))


# 容器类型
print(type([1, 2, 3, 'a', 'bc']))
print(type((1, 2, 3, 'abc')))
values = ['abc', 1, 2, 3.]
print(type(values[3]))
print(type(set(['a', 1, 2.])))
print(type({'a':123, 4:'bcd', 5:'efg'}))


# 函数
def func(): print(100)
print(type(func))


# 模块
print(type(string))


# 自定义类型与类型实例
class Cls: pass
print(type(Cls))
cls = Cls()
print(type(cls))


# 变量赋值
try:
    print(x)    # 变量必须先赋值再使用
except NameError:
    print("NameError: name 'x' is not defined")
x = 100
x = 'abcd'  # x的类型不受限制

# -*- coding: utf-8 -*-


import string


# strip去除空格
s = ' abcd efg  '
print(s.strip())
print(s.lstrip())
print(s.rstrip())
print(s)


# 字符串连接
print('abc_' + 'defg')
s = 'abcdefg'
s += '\nhijk'
print(str)


# 大写小
s = 'abc defg'
print(s.upper())
print(s.upper().lower())
print(s.capitalize())


# 位置和比较
s_1 = 'abcdefg'
s_2 = 'abdefgh'
print(s_1.index('bcd'))
try:
    print(s_1.index('bce'))
except ValueError:
    print('ValueError: substring not found')
print(s_1 == s_1)   # cmp函数被Python3移除了
print(s_1 > s_2)
print(s_2 > s_1)


# 分割和连接
s = 'abc,def,ghi'
print(s.split(','))
s = '123\n456\n789'
numbers = s.splitlines()
print(numbers)
print('-'.join(numbers))


# 常用判断
s = 'abcdefg'
print(s.startswith('abc'))
print(s.endswith('efg'))
print('abcd1234'.isalnum())
print('\tabcd1234'.isalnum())
print('abcd'.isalpha())
print('12345'.isdigit())
print('  '.isspace())
print('acb125'.islower())
print('A1B2C'.isupper())
print('Hello world!'.istitle())


# 数字到字符串
print(str(5))
print(str(5.))
print(str(-5.23))
print(int('1234'))
print(float('-23.456'))


# 格式化字符串
print('Hello %s!' % 'world')
print('%d-%.2f-%s' % (4, -2.3, 'hello'))

# -*- coding: utf-8 -*-


# if判断
a = 100
b = 200
c = 300
if c == a:
    print(a)
elif c == b:
    print(b)
else:
    print(c)


# None的判断
x = None
if x is None:
    print 'x is None'
if not x:
    print 'x is None'


# for循环
s = 0
for i in range(0, 101):
    s += i
print(s)


# while循环
s = 0
i = 0
while i <= 100:
    s += i
    i += 1
print(s)


# continue/pass/break
for i in range(0, 100):
    if i < 10:
        pass
    elif i < 30:
        continue
    elif i < 35:
        print(i)
    else:
        break


# -*- coding: utf-8 -*-


# 函数定义和默认参数
def func(x, y = 500):
    print(x, y)


func(150)
func(100, 200)
func(y = 300, x = 100)


# 可变参数
def func(name, *numbers):
    print(name)
    print(numbers)


func('Tom', 1, 2, 3, 4)


# 关键字参数
def func(name, **kvs):
    print(name)
    print(kvs)


func('Jack', china = 'Beijing', uk = 'London')


# 命名关键字参数
def func(*, china, uk): # *用于和普通参数做分割,*args一样效果
    print(china, uk)


func(china = 'Beijing', uk = 'London')  # 必须传入参数名


# 复杂情况
def func(a, b, c = 0, *args, **kvs):
    print(a, b, c, args, kvs)


func(1, 2)
func(1, 2, 3)
func(1, 2, 3, 'a', 'b')
func(1, 2, 3, 'a', 'b', china = 'Beijing', uk = 'London')
func(1, 2, 3, *('a', 'b'), **{'china':'Beijing', 'uk':'London'})


# 递归的经典例子!
def fib(n):
    if n < 1:
        raise ValueError
    elif (n == 1) or (n == 2):
        return 1
    else:
        return fib(n - 1) + fib(n - 2)


print(fib(1))
print(fib(2))
print(fib(3))
print(fib(4))
print(fib(5))
print(fib(6))

li = [1, 2, 3, '456', [1, 2, 3], {1: 'one', 2: 'two'}]
print(type(list))
print(type(li))


# 元素访问
print(li[0])
print(li[-1])   # li[len(li) - 1]
print(li[-2])   # li[len(li) - 2]


# 查找元素位置
print(li.index('456'))
print(li.index([1, 2, 3]))
# print(li.index(-1))


# 添加元素
l_a = [1, 2, 3]
l_a.append(4)
l_a.append(5)
l_b = [6, 7, 8]
l_a.extend(l_b) # 试下用append是什么结果
print(l_a)


l_a = []
if not l_a:
    print('Empty')  # not XX和is None不是一回事


if len(l_a) == 0:
    print('Empty')


for i in li:
    print(i)
for i in range(len(li)):
    print(li[i])


t = (1, 2, 3, '456')
print(type(t))
# t[0] = 'a'
# t.append('x')


del(li[-1]) # del(list[index])
del(li[1])
del(li[-2])
print(li)

d = {'a': 1, 'b': 2, 1: 'one', 2: 'two', 3: [1, 2, 3]}
print(type(dict))
print(type(d))
print(d)


# 访问元素
print(d['a'])
print(d[1])
print(d[3])


# 判断key是否存在
print('two' in d)
print(3 in d)
del(d[3])   # del(dict[key])


print(len(d))


d[3] = [1, 2, 3, 4]
d[3] = '1234'


# 遍历
for key in d:
    print(d[key])
print('...')
for k, v in d.items():
    print(k, v)
print('...')
keys = d.keys()
print(type(keys))
print(keys)

初识defaultdict

之前在使用字典的时候, 用的比较随意, 只是简单的使用dict.
然而这样在使用不存在的key的时候发生KeyError这样的一个报错, 这时候就该defaultdict登场了.

如何使用defaultdict

可以这样

from collections import defaultdictd1 = defaultdict(int)

或者这样

import collectionsd1 = collections.defaultdict(int)

defaultdict与dict实例化字典类型的区别

使用defaultdict任何未定义的key都会默认返回一个根据method_factory参数不同的默认值, 而相同情况下dict()会返回KeyError.
比较下面代码:

d1 = dict()d2 = defaultdict(list)print(d1['a'])print(d2['a'])

defaultdict的构造

python官方文档中对defaultdict的定义如下:

class collections.defaultdict([default_factory[, ...]])

python官方文档中对defaultdict的解释如下:

defaultdicdict subclass that calls a factory function to supply missing values

default_factory 接收一个工厂函数作为参数, 例如int str list set等.
defaultdict在dict的基础上添加了一个missing(key)方法, 在调用一个不存的key的时候, defaultdict会调用__missing__, 返回一个根据default_factory参数的默认值, 所以不会返回Keyerror.

Example

Example 1

s = 'mississippi'd = defaultdict(int)for k in s:  d[k] += 1print(d)

Example 2

s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]d = defaultdict(set)for k, v in s:  d[k].add(v)print(d)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。