如何将python遍历的数据保存成一个字典

Python08

如何将python遍历的数据保存成一个字典,第1张

#! /usr/bin/python

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

dictionary = {‘a’:'one’,'b’:'two’,'c’:'three’}    #创建字典

dictionary1 = {1:’test1′,2:’test2′,3:’test3′}     #创建字典

print dictionary,dictionary1                      #打印输出字典

print dictionary['b']                             #打印输出字典dictionary中key为b的值

dictionary['s'] = ‘test’   #添加

print dictionary

dictionary['a'] = ‘mod’   #key存在就修改

print dictionary

dictionary['a'] = ‘one’

dictionary.pop(‘s’)   #删除key对应的值

print dictionary

for i in dictionary:   #遍历字典

print ‘dictionary[%s] = ‘ % i ,dictionary[i]

print dictionary.keys()   #返回字典中key列表

print dictionary.values()   #返回字典中value列表

print dictionary.get(‘c’)   #返回key对应的值

#dictionary.update(dictionary1)   #把字典dictionary1更新到字典dictionary中,dictionary中原有内容保持不变。

#print dictionary   #测试这两句的时候将前面的#去掉即可

print ‘使用copy()前的结果’,dictionary1

dictionary1 = dictionary.copy()   #将dictionary的内容copy()到dictionary1中

print ‘使用copy()后的结果’,dictionary1

print sorted(dictionary.items())   #sorted()为字典排序

dictionary.clear()       #清空字典

print dictionary

相信这段代码对你有所帮助吧。

文章来源:http://www.skzbz.com/11

字典是python中一种常见的数据格式,我们也常需要对这些数据做缓存。一般采用保存到redis实现。 但是redis库的set, get方法不支持字典,只支持二进制或者字符串。 所以网上一般都采用转换为字典或字符串的形式,比较麻烦。

其实redis 的还支持hash处理。

例子如下: