字典错误

时间:2015-07-02 10:02:34

标签: python string mongodb dictionary pymongo

我正在尝试从redis获取哈希并将其存储到mongoDB数据库

import pymongo
//mongoDB, redis connection etc 'r' is redis object
data = r.hget('temp', 'temp')
db.collection.insert(data)

我收到这个pymongo错误:

Traceback (most recent call last):
  File "try.py", line 45, in <module>
    collection.insert(data)
  File "/home/amitt001/mycodes/clay/proj-1/envplay/lib/python2.7/site-packages/pymongo/collection.py", line 1926, in insert
    check_keys, manipulate, write_concern)
  File "/home/amitt001/mycodes/clay/proj-1/envplay/lib/python2.7/site-packages/pymongo/collection.py", line 430, in _insert
    gen(), check_keys, self.codec_options, sock_info)
  File "/home/amitt001/mycodes/clay/proj-1/envplay/lib/python2.7/site-packages/pymongo/collection.py", line 405, in gen
    doc['_id'] = ObjectId()
TypeError: 'str' object does not support item assignment

数据的字符串类型如何?在做的时候:

print data

{'offsite/domains': 1, 'scheduler/dequeued': 104, 'log_count/INFO': 7, 'downloader/response_count': 104, 'start_time': datetime.datetime(2015, 7, 2, 9, 42, 34, 128090), 'scheduler/dequeued/memory': 104, 'offsite/filtered': 2, 'scheduler/enqueued': 104, 'finish_time': datetime.datetime(2015, 7, 2, 9, 42, 53, 894133), 'downloader/request_bytes': 43108, 'request_depth_max': 4}

print(type(data))
<type 'str'> 

为什么mongoDB没有存储dict?类型检查的dict如何转换为字符串?

编辑: 输出

data = ast.literal_eval(data)
print data, type(data)
print(repr(data))

enter image description here

1 个答案:

答案 0 :(得分:1)

变量data是字符串。你需要将它转换为python字典。那是什么 ast.literal_eval确实如此。

import ast
data = r.hget('temp', 'temp')
db.collection.insert(ast.literal_eval(data))

预计print(data)的结果。

>>> data = "{'foo': 1, 'bar': 1}"
>>> print(data)
{'foo': 1, 'bar': 1}
>>> d = {'foo': 1, 'bar': 1}
>>> print(d)
{'foo': 1, 'bar': 1}
>>> type(data)
<class 'str'>
>>> type(d)
<class 'dict'>

正如您所看到的,data是字符串而d是字典,但使用print我们会得到相同的输出。