如何在 python 中动态更新字典 (key/data)

How to dynamically update dictonary (key/data) in python

这是一个测试文件,我正在其中试用 excel 读取包,这就是变量被命名的原因 lazily.I 我正在尝试从 excel 文件中读取数据并将其转换为 JSON,但我无法遍历数据并将其放入字典。

import xlrd
from collections import OrderedDict
import json


# Open the workbook and select the first worksheet
wb = xlrd.open_workbook('Test_Book.xlsx')
sh = wb.sheet_by_index(0)



data_list = []


data = OrderedDict()

for i in range(1, sh.nrows):

    for j in range(1, sh.ncols+1):
        data[sh.row_values(0)[i-1]] = sh.row_values(i)[j-1]

        #data[j] = ({sh.row_values(0)[j-(sh.nrows - sh.ncols)] : sh.row_values(j)})

        #print("I = "+i.__str__())
        #print("J = "+j.__str__())
    data_list.append(data)

# Serialize the list of dicts to JSON
j = json.dumps(data_list)



with open('data.json', 'w') as f:
    f.write(j)

我试过嵌套for循环,但数据顺序不正确。 这些键似乎工作正常,但当我尝试对数据进行同样的操作时,它不起作用。 (这个我不得不一行接一行地手动添加数据,第二部分是我尝试动态添加数据的地方) 这是它需要的样子。

OrderedDict([('ID', 2.0), ('Make', 'Toyota'), ('Model', 'Corolla'), ('Milage', 15956.0)])
OrderedDict([('ID', 3.0), ('Make', 'Jeep'), ('Model', 'Compass'), ('Milage', 114885.0)])
OrderedDict([('ID', 4.0), ('Make', 'Honda'), ('Model', 'Pilot'), ('Milage', 3830.0)])

这是我的代码执行的样子

OrderedDict([('ID', 5.0), ('Make', 'Subaru'), ('Model', 'Outback'), ('Milage', 20424.0), ('Condition', 'Fair')])
OrderedDict([('ID', 5.0), ('Make', 'Subaru'), ('Model', 'Outback'), ('Milage', 20424.0), ('Condition', 'Fair')])
OrderedDict([('ID', 5.0), ('Make', 'Subaru'), ('Model', 'Outback'), ('Milage', 20424.0), ('Condition', 'Fair')])

您只在所有循环外初始化 data OrderedDict 一次,而在内部似乎您不断地一次又一次地更改相同键的值,这将继续更改相同的 OrderedDict 对象,最后您将相同的 OrderedDict 对象附加到 data_list.

您需要为每次迭代(外循环)创建一个新的 data OrderedDict。

尝试类似 -

for i in range(1, sh.nrows):
    data = OrderedDict()
    for j in range(1, sh.ncols+1):
        data[sh.row_values(0)[j-1]] = sh.row_values(i)[j-1]
        data3.append(sh.row_values(i)[j-1])

        #data[j] = ({sh.row_values(0)[j-(sh.nrows - sh.ncols)] : sh.row_values(j)})
        #print("I = "+i.__str__())
        #print("J = "+j.__str__())
    data_list.append(data)

此外,您似乎没有对 data3 做任何事情,为什么它在那里?如果您不需要它,请将其删除。

在python中,大部分变量都是引用,所以存储的时候要小心:

>>> list_of_lists = []
>>> l = [1, 2, 3]           # Creating a random list
>>> list_of_lists.append(l) # Storing it
>>> l[1] = 'Blob'           # Updating it! Here's the problem.
>>> list_of_lists.append(l) # Storing it again
>>> l = ['New', 'List']     # Creating a new list
>>> list_of_lists.append(l) # Storing it
>>> list_of_lists           # Notice that the 2 first list are equals
[[1, 'Blob', 3], [1, 'Blob', 3], ['New', 'List']]
>>> list_of_lists[0] is list_of_lists[1]
True

在你的例子中,你只有 一个 data 对象,并且你在 data_list 中存储了 3 个对它的引用。您必须在每个循环中通过重新初始化为空 OrderedDict 来“重置”您的 data 变量以获得预期结果:

for i in range(1, sh.nrows):
    data = OrderedDict () # here
    for j in range(1, sh.ncols+1):
        data[sh.row_values(0)[j-1]] = sh.row_values(i)[j-1]
        data3.append(sh.row_values(i)[j-1])
    data_list.append(data)

另一种方法(less pythonic,IMO)是在将 data 变量存储到 data_list:

之前显式创建一个副本
for i in range(1, sh.nrows):
    for j in range(1, sh.ncols+1):
        data[sh.row_values(0)[j-1]] = sh.row_values(i)[j-1]
        data3.append(sh.row_values(i)[j-1])
    data_list.append(data.copy ())