1. python:如何將字典中的值寫入文件
yourDict={'1000':{'1':['a','b','c','d'],'2':['e','b','c','a']},'2000':{'1':['c','d','c','d'],'2':['a','a','c','d']}}
out=open('out.xls','w')
for key in yourDict:
out.write(key)
for key2 in yourDict[key]:
out.write('\t')
out.write(key2+'\t')
out.write('\t'.join(yourDict[key][key2] ))
out.write('\n')
最後xls轉存為csv即可
2. python中以字典為元素的列表怎麼寫入文本文件
##調用json.mp函數就行了,下面是一個例子
import json
##將FileName指定為你的文件的實際路徑
FileName='t.txt'
lst=[{'name':'lili','age':25},{'name':'gg','age':18}]
with open(FileName,'w') as f:
json.mp(lst,f)
3. python字典的值如何列印
推測你的意圖,做了一些修改:
classChinese:
def__int__(self):
self._number=None
defset_number(self,value):
ifvalue>=1andvalue<=5:
self._number=value
else:raiseValueError("Numbernotrecognized")
defchinese(self):
number2chinese={1:"一",2:"二",3:"三",4:"四",5:"五"}
returnnumber2chinese[self._number]
defset_chinese(self,value):
chinese2number={"一":1,"二":2,"三":3,"四":4,"五":5}
ifvalueinchinese2number:
self._number=chinese2number[value]
else:
raiseValueError("Chinesenumeralnotrecognized")
a=Chinese()
a.set_number(3)
print(a._number)
print(a.chinese())
b=Chinese()
b.set_chinese("五")
print(b._number)
print(b.chinese())
運行環境Python 2.7.16, 結果:
4. 請問如何用python將字典轉換到txt文本中
1、首先打開python的一個文件。
5. python如何將字典寫入文件(字典中存放的是一些二維數組),再從上述文件讀數據到字典
importpickle
dictfile=open("myfile",'wb')
mydict={"a":[[1,2],[3,4]],"b":[[5,6],[7,8]]}
pickle.mp(mydict,dictfile)
dictfile.close()
dictfile=open("myfile",'rb')
readdict=pickle.load(dictfile)
print(readdict)
6. Python如何將字典中的數據存入到文檔中
dic[key]的value是string么?我看你這裡面有一行代碼,存的好像是float
dic[tmp[0]]+=float(tmp[3])
join這個函數只能給string類型的用
7. Python怎麼將列表,或者txt文件輸出轉化為字典啊
讀入每一行,按逗號分割,然後存到dict里就可以了。。
對於上一個問題,你把encoding設為utf-8就好了。。
我就幫你把代碼寫了吧,也算是解決了上一個問題了。。(求採納orz..)
Code
in
python
3
rate1
=
open('1.txt',
'r',
encoding='utf-8')
dic
=
dict()
for
line
in
rate1:
line
=
line.strip().split(',')
dic[line[0]]
=
line[1]
print(dic)
rate1.close()
8. python mysql 字典 怎麼列印
Python的MySQLdb模塊是Python連接MySQL的一個模塊,默認查詢結果返回是tuple類型,只能通過0,1..等索引下標訪問數據默認連接資料庫:
復制代碼 代碼如下:
MySQLdb.connect(
host=host,
user=user,
passwd=passwd,
db=db,
port=port,
charset='utf8'
)
查詢數據:
復制代碼 代碼如下:
cur = conn.cursor()
cur.execute('select b_id from blog limit 1')data = cur.fetchall()
cur.close()
conn.close()
列印:
復制代碼 代碼如下:
for row in data:
print type(row)
print row
執行結果:
復制代碼 代碼如下:
<type 'tuple'>
(1L,)
為tuple類型。
我們可以這么干使得數據查詢結果返回字典類型,即 欄位=數據導入模塊
復制代碼 代碼如下:
import MySQLdb.cursors
在連接函數里加上這個參數 cursorclass = MySQLdb.cursors.DictCursor 如:
復制代碼 代碼如下:
MySQLdb.connect(
host=host,
user=user,
passwd=passwd,
db=db,
port=port,
charset='utf8',
cursorclass = MySQLdb.cursors.DictCursor
)
再重新運行腳本,看看執行結果:
復制代碼 代碼如下:
<type 'dict'>
{'b_id': 1L}
搞定!
注意,在連接的時候port如果要指定則值必須是整型,否則會出錯!
9. python如何將文本文件內容添加到字典
d={}
forlineinfileobj:
key,value=line.strip().split(',')
10. python列印字典(鍵值對)的時候為什麼會莫名奇妙多出一行,我是從文件讀的。
defreadfile():
forlninfile.readlines():
kv=ln.strip().split(':')
dt[kv[[0]]=kv[1]