在Python3中,如何将嵌套字典附加到搁置文件中,同时增加了使用for循环的难度?

2024-10-05 13:23:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图找出如何用嵌套字典填充搁置文件。在

以下是我的要求:

  1. 创建名为的搁置文件人.db在
  2. 在搁置文件中添加新的人员(人员1、人员2等)。在
  3. 使用for循环遍历'attributes',这样我就不需要逐行写出冗长的代码来填充到搁置文件中。在
  4. 需要引用搁置文件数据以备将来使用

这是我想附加到搁置文件的键/值格式。在

person_1 = { 'name': 'Bob', 'type': 'employee', 'attributes':
        [{'game': 'basketball', 'high score': '100', 'time': '3.34'},
        {'game': 'bridge', 'high score': '10', 'time': '30.34'},
        {'game': 'foosball', 'high score': '2', 'time': '24'}]
        '''
        50+ other attributes
        '''
        }

# Example: s['person_1]['attributes'][2]['time'] would call out '24'.
# 's' is from 's = shelve.open('people')'

我有一本字典dictPeople.py文件(使用pprint()创建,该文件包含用户1等的信息 我只提取了所需数据的一小部分。在

我尝试了以下操作,但是我得到一个无效的密钥错误。在

^{pr2}$

结果,我得到了键错误,因为我不允许引用键/值 用我能和字典配对的方法。然而,疯狂的是我可以 尝试写入时使用相同的格式调用db文件中的值。在

例如: 我可以使用以下方法从.db文件中读取数据:

x = s['person_1']['name']
print(x)

但是!我不能用那种格式写入.db文件,否则我得到的密钥无效 错误。没道理!在

s['person_1']['name'] = 'Bob'
# Returns invalid key entry.  Makes no sense.

因此,我尝试使用以下方法提取数据并填充db文件:

s[person] = {   'name': dictPeople.person_1['name'],
            'type': dictPeople.person_1['type'],
for attribute in range(0, len(dictPeople['attributes'][attribute])):
    ['game':  dictPeople['attributes'][attribute]['game'],
    'high score': dictPeople['attributes'][attribute]['high score'],
    'time': dictPeople['attributes'][attribute]['time']]

}

但是,这显然不起作用,因为for循环。我该怎么做?在

  1. 我正在想办法从字典中提取数据dictPeople.py文件 把它储存在人.db文件。在
  2. 我正在尝试为人.db随着更多人的加入而归档。在
  3. 我需要使用for循环,因为我需要添加50多个属性。在
  4. 我未来的步骤是修改我提取并用于填充人.db文件,但我的第一步是,至少,提取,然后 填充人.db文件。在

Tags: 文件数据namegamefordb字典time

热门问题