2014-02-18 82 views
0

我試圖訪問一個python列表的元素後,我做了一行行JSON對象解析,我無法訪問值。如何訪問python字典

例如:

data1 = [{u'time': 136.648, u'name': u'machine', u'value': 71.3}]; 
data1 = str(data1)[1:-1] 
print data1 
print data1 ['time'] 

抓取從DATA1的 '時間' 值給出了一個錯誤:

TypeError: string indices must be integers, not str 
{u'name': u'machine', u'value': 71.3, u'time': 136.648} 

可選地以下工作正常:

data2 = '{"time": 136.648, "name": "machine", "value":71.3}' 
data2 = json.loads(data2) 
print data2 
print data2 ['time'] 

輸出:

{u'name': u'machine', u'value': 71.3, u'time': 136.648} 
136.648 

爲什麼一個工作,另一個不工作? data1和data2似乎都是一樣的。

我想分析這個名單,這樣我可以訪問它裏面的數據:

data = [{u'time': 136.648, u'name': u'machine', u'value': 71.3}, {u'time': 138.648, u'name': u'machine2', u'value': 71.56}]; 

回答

3

在第一種情況下,您的字符串爲"{u'name': u'machine', u'value': 71.3, u'time': 136.648}"。這不是一本字典 - 它是一個字符串。您試圖訪問字符串的字符串鍵,但字符串沒有字符串鍵,它們只有整數索引。

在第二種情況下,您解析字符串(通過JSON)並獲得一個字典,然後您可以訪問該字典。

或許這將幫助:

>>> a = [{u'time': 136.648, u'name': u'machine', u'value': 71.3}] 
>>> b = str(a)[1:-1] 
>>> c = '{"time": 136.648, "name": "machine", "value":71.3}' 
>>> d = json.loads(c) 

>>> a 
[{u'name': u'machine', u'value': 71.3, u'time': 136.648}] 
>>> type(a) 
<type 'list'> 
>>> a[0] 
{u'name': u'machine', u'value': 71.3, u'time': 136.648} 
>>> a[0]['time'] 
136.648 

>>> b 
"{u'name': u'machine', u'value': 71.3, u'time': 136.648}" 
>>> type(b) 
<type 'str'> 
>>> b[0] 
'{' 
>>> b['time'] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: string indices must be integers, not str 

>>> c 
'{"time": 136.648, "name": "machine", "value":71.3}' 
>>> type(c) 
<type 'str'> 
>>> c[0] 
'{' 
>>> c['time'] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: string indices must be integers, not str 

>>> d 
{u'name': u'machine', u'value': 71.3, u'time': 136.648} 
>>> type(d) 
<type 'dict'> 
>>> d['time'] 
136.648 
+0

爲什麼我可以問一個downvote? – Claudiu

0

在你的詞典列表的第一種情況:擺脫data1= str(data1)[1:-1]和使用print data1[0]['time']

+0

'data1'是在第一個例子中的字符串。 – user2357112

+0

是和不是@ user2357112。第一行是第一行字典,但第二行將其轉換爲字符串,並刪除了括號 – mhlester

+0

確定這是訪問它的最簡單方法 – method3325177

2

當你這樣做:

data1 = [{u'time': 136.648, u'name': u'machine', u'value': 71.3}]; 
data1 = str(data1)[1:-1] 
print data1 # string 
print type(data1)  # => prints out <type 'str'> 
print data1 ['time'] # accessing a string without an index doesn't work 

您試圖訪問一個字符串的索引。

的,因爲你已經加載它作爲一個字符串是合法的JSON數據如下工作:

data2 = '{"time": 136.648, "name": "machine", "value":71.3}' 
data2 = json.loads(data2) 
print data2 
print type(data2) # => prints out <type 'dict'> 
print data2 ['time'] 

爲什麼data1不起作用:

data2的作品,因爲它是一個字典,並data1是一個字符串,並且不起作用,因爲您無法訪問除數字索引或切片以外的任何字符串。

-1

這個代碼在計算器發現應解碼此字符串爲您(Fastest way to convert a dict's keys & values from `unicode` to `str`?

ATA = { u'spam': u'eggs', u'foo': frozenset([u'Gah!']), u'bar': { u'baz': 97 }, 
    u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])]} 

def convert(data): 
    if isinstance(data, basestring): 
     return str(data) 
    elif isinstance(data, collections.Mapping): 
     return dict(map(convert, data.iteritems())) 
    elif isinstance(data, collections.Iterable): 
     return type(data)(map(convert, data)) 
    else: 
     return data 

print DATA 
print convert(DATA) 
# Prints: 
# {u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])], u'foo': frozenset([u'Gah!']), u'bar': {u'baz': 97}, u'spam': u'eggs'} 
# {'bar': {'baz': 97}, 'foo': frozenset(['Gah!']), 'list': ['list', (True, 'Maybe'), set(['and', 'a', 'set', 1])], 'spam': 'eggs'} 
+0

提問者不是試圖將unicode元素轉換爲'str'。 – user2357112

+0

這是一種方式:我的最終目標是解析此列表,以便我可以訪問其中的數據 – Epitouille

+0

他可以用unicode完成這一切。 – user2357112