2015-06-30 154 views
1

比方說,我將字典的值存儲在JSON文件中。這裏是簡化的代碼:從JSON文件中讀取數字鍵

test = {} 
for i in range(10): 
    for j in range(15): 
     test['{},{}'.format(i, j)] = i * j 

with open('file1.json', 'w') as f: 
    json.dump(test, f) 

我很難從這個文件回讀。我怎樣才能從這個文件讀回字典中的元素,如鍵[i,j]和值爲i * j? 我用簡單

with open('file1.json', 'r') as f: 
    data2 = json.load(f) 
+2

你能說明你如何讀回你的'json'文件嗎? – Kasramvd

+1

@ kasra:我做了,謝謝你的幫助。 – NNsr

+0

所以你的意思是*辛苦時間*它適合我!實際上這個代碼沒有問題!但是你的預期輸出是什麼? – Kasramvd

回答

1

你的意思是這樣嗎?

with open('file1.json', 'r') as f: 
    data2 = {tuple(int(x) for x in k.split(',')): v 
     for (k, v) in json.load(f).items()} 
+0

是的,謝謝。這實際上適用於[i,j]格式的密鑰。無論如何要把它擴展到密鑰格式爲[i,j,k,l,m]的情況?再次感謝你。 – NNsr

+1

它應該可以隨機使用任意數量的元素。 – zero323

+1

太棒了;謝謝。我讓它太複雜了。謝謝! – NNsr

1

您的代碼將返回一個字典包含Unicode項和值,如果你想獲得一個字典包含加載文件後,就可以使用json.dumps整數值:

import json 
test = {} 
for i in range(10): 
    for j in range(15): 
     test['{},{}'.format(i, j)] = i * j 

with open('file1.json', 'w') as f: 
    json.dump(test, f) 

with open('file1.json', 'r') as f: 
    data2 = json.load(f) 

print json.dumps(data2) 

結果:

{"1,8": 8, "1,9": 9, "1,6": 6, "1,7": 7, "1,4": 4, "1,5": 5, "1,2": 2, "1,3": 3, "1,0": 0, "1,1": 1, "7,6": 42, "7,7": 49, "5,8": 40, "5,9": 45, "3,8": 24, "3,9": 27, "5,2": 10, "5,3": 15, "5,0": 0, "3,7": 21, "3,0": 0, "5,7": 35, "3,2": 6, "3,3": 9, "3,14": 42, "3,12": 36, "3,13": 39, "3,10": 30, "3,11": 33, "2,8": 16, "5,14": 70, "5,10": 50, "5,11": 55, "5,12": 60, "5,13": 65, "0,8": 0, "4,8": 32, "0,13": 0, "0,12": 0, "0,11": 0, "0,10": 0, "0,14": 0, "6,9": 54, "6,8": 48, "6,1": 6, "6,0": 0, "6,3": 18, "6,2": 12, "6,5": 30, "6,4": 24, "6,7": 42, "6,6": 36, "6,14": 84, "6,11": 66, "6,10": 60, "6,13": 78, "6,12": 72, "8,9": 72, "8,8": 64, "8,7": 56, "8,6": 48, "8,5": 40, "8,4": 32, "8,3": 24, "8,2": 16, "8,1": 8, "8,0": 0, "5,1": 5, "2,13": 26, "3,4": 12, "3,5": 15, "3,6": 18, "0,7": 0, "0,6": 0, "0,5": 0, "0,4": 0, "0,3": 0, "0,2": 0, "0,1": 0, "0,0": 0, "5,6": 30, "0,9": 0, "3,1": 3, "1,10": 10, "1,11": 11, "1,12": 12, "1,13": 13, "2,9": 18, "5,4": 20, "2,5": 10, "2,4": 8, "2,7": 14, "2,6": 12, "2,1": 2, "2,0": 0, "2,3": 6, "2,2": 4, "4,3": 12, "4,2": 8, "4,1": 4, "4,0": 0, "4,7": 28, "4,6": 24, "4,5": 20, "4,4": 16, "2,11": 22, "2,10": 20, "4,9": 36, "2,12": 24, "2,14": 28, "1,14": 14, "5,5": 25, "8,13": 104, "8,12": 96, "8,11": 88, "8,10": 80, "8,14": 112, "7,12": 84, "7,13": 91, "7,10": 70, "7,11": 77, "7,14": 98, "4,14": 56, "4,13": 52, "4,12": 48, "4,11": 44, "4,10": 40, "7,8": 56, "7,9": 63, "9,4": 36, "9,5": 45, "9,2": 18, "9,3": 27, "9,0": 0, "9,1": 9, "7,0": 0, "7,1": 7, "7,2": 14, "7,3": 21, "7,4": 28, "7,5": 35, "9,8": 72, "9,9": 81, "9,6": 54, "9,7": 63, "9,10": 90, "9,11": 99, "9,12": 108, "9,13": 117, "9,14": 126}