使用Openpyxl在Python中创建嵌套字典

时间:2018-07-15 18:14:33

标签: python dictionary openpyxl

尝试在Python中构建字典,该字典是通过使用Openpyxl遍历Excel文件而创建的,其中键是人的名字,值是字典项的列表,其中每个键是Location,值是起始和结束数组。

这是Excel文件:

enter image description here

这就是我想要的:

people = {
  'John':[{20:[[2,4],[3,5]]}, {21:[[2,4]]}],
  'Jane':[{20:[[9,10]]},{21:[[2,4]]}]
}

这是我当前的脚本:

my_file = openpyxl.load_workbook('Book2.xlsx', read_only=True)
ws = my_file.active

people = {}
for row in ws.iter_rows(row_offset=1):
  a = row[0] # Name
  b = row[1] # Date
  c = row[2] # Start
  d = row[3] # End
  if a.value:  # Only operate on rows that contain data 
    if a.value in people.keys():  # If name already in dict
      for k, v in people.items():
        for item in v:
          #print(item)
          for x in item:
            if x == int(b.value):
              print(people[k])
              people[k][0][x].append([c.value,d.value])
            else:
              #people[k].append([c.value,d.value])  # Creates inf loop
    else:
      people[a.value] = [{b.value:[[c.value,d.value]]}]

哪个成功创建了这个:

{'John': [{20: [[2, 4], [9, 10]]}], 'Jane': [{20: [[9, 10]]}]}

但是当我取消注释else:块之后的行以尝试向初始列表中添加新的Location字典时,它将创建一个无限循环。

if x == int(b.value):
   people[k][0][x].append([c.value,d.value])
else:
   #people[k].append([c.value,d.value])  # Creates inf loop

我敢肯定,还有一种更Python化的方式可以做到这一点,但是很困在这里,寻找正确的方向。此处的结果是分析所有字典项,以便每个人和每个位置的开始/结束重叠。因此,约翰在20位置的3.00-5.00起点与他在2.00-4.00相同位置的起点/终点重叠

2 个答案:

答案 0 :(得分:1)

您可以为此使用Pandas库。该解决方案的核心是嵌套的字典理解,每个字典都使用groupby。如下所示,您可以使用函数来处理嵌套,以提高可读性/维护性。

import pandas as pd

# define dataframe, or df = pd.read_excel('file.xlsx')
df = pd.DataFrame({'Name': ['John']*3 + ['Jane']*2,
                   'Location': [20, 20, 21, 20, 21],
                   'Start': [2.00, 3.00, 2.00, 9.00, 2.00],
                   'End': [4.00, 5.00, 4.00, 10.00, 4.00]})

# convert cols to integers
int_cols = ['Start', 'End']
df[int_cols] = df[int_cols].apply(pd.to_numeric, downcast='integer')

# define inner dictionary grouper and split into list of dictionaries
def loc_list(x):
    d = {loc: w[int_cols].values.tolist() for loc, w in x.groupby('Location')}
    return [{i: j} for i, j in d.items()]

# define outer dictionary grouper
people = {k: loc_list(v) for k, v in df.groupby('Name')}

{'Jane': [{20: [[9, 10]]}, {21: [[2, 4]]}],
 'John': [{20: [[2, 4], [3, 5]]}, {21: [[2, 4]]}]}

答案 1 :(得分:1)

看来您想得太多了;默认字典的组合应该可以解决问题。

from collections import defaultdict
person = defaultdict(dict)

for row in ws.iter_rows(min_row=2, max_col=4):
    p, l, s, e = (c.value for c in row)
    if p not in person:
        person[p] = defaultdict(list)
    person[p][l].append((s, e))
相关问题