【问题标题】:Is it possible to store data within a key, within another key in a dictionary?是否可以将数据存储在一个键中,一个字典中的另一个键中?
【发布时间】:2020-08-03 16:38:16
【问题描述】:

我有一个作为员工姓名首字母的键的字典。我需要为每个员工(键)存储一年中每个月的数据。是否可以将每个月作为键存储在每个员工键中,然后存储每个月的数据?

如果有帮助,这是我的代码:

#Creates dictionary, each employee as a key
employee_dict = dict((z[0],list(z[1:])) for z in zip(employee_list))

for key, value in employee_dict.items():
    for i in data_to_store_for_each_employee_array:
        if i[0] == key:
            employee_dict[key].append(i[1])

我的程序使用 configparser 从 txt 文件中读取员工姓名缩写。然后它将员工姓名缩写存储到一个列表中。缩写很容易改变,所以我无法将它们硬编码到我的程序中

我的字典现在是这样的:

dict_items([('TS', []), ('IR', []), ('RD', []), ('SP', []), ('RA', []), ('WN', []), ('KT', [])])

I was hoping to get it to look something like:
dict_items([('TS': January[], February[], March[]....) {and so on, for each pair of initials} 

【问题讨论】:

  • 您能否举一个小例子说明字典当前的外观以及您期望它的外观?
  • 是的,你可以有任何你想要的嵌套级别 {'employee_name':{'month-year-key': data-you-want-to-store}}
  • 是否可以使用for循环为txt文件中的每个员工创建这个?

标签: python list dictionary key storage


【解决方案1】:

您可以尝试创建一个字典,其中每个都有一个字典值(嵌套字典)。这就是它的样子:

info_dict = {
    'employee_1': {'January': #data, 
        'February':#data}
    'employee_2': {'January': #data, 
        'February':#data}
    'employee_3': {'January': #data, 
        'February':#data}
    }

如果您有一个员工姓名的 .txt 文件,那么您会将其转换为键并将值添加到特定的员工键:

employees = []
dictionary = {}
nested_dictionary = {}

filename = '#file_name'
with open(filename, 'r') as f_obj:
   lines = f_obj.readlines()
   for line in lines:
      name_lst = line.split(' ')
      for name in name_lst:
          employees.append(name)
    
for employee in employees:
   dictionary[employee] = None #Because I don't know where you're data is coming from...

print(dictionary)

【讨论】:

  • 感谢您的回复!我有一个列出员工的 .txt 文件(员工很容易发生变化,所以我无法将员工硬编码到程序中)。使用 configparser,我将员工姓名存储到 Python 中的列表中。至于我需要存储的数据,我正在使用 OpenPyxl 扫描一个 excel 文档。
  • 我编辑了我的回复以允许您从 .txt 文件中收集员工姓名。这是一篇教程文章,我认为它可以帮助您了解 OpenPyxl 部分:realpython.com/openpyxl-excel-spreadsheets-python。我希望这可以帮助您入门。
  • 非常感谢!我能够读取 .txt 文件并将员工姓名缩写存储到 python 中的列表中,并且我已经在我的程序中实现了这一点。是否可以创建一个 for 循环,为每个员工创建一个嵌套字典,以将每个首字母存储为一个键,每个月作为第一个键中的另一个键,然后是每个月的数据?
  • 是的,这是可能的,但您必须使用许多 for 循环,因为您要遍历多个字典。
猜你喜欢
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多