【问题标题】:Python dictionary appending key:value pairsPython字典附加键:值对
【发布时间】:2013-11-07 16:37:29
【问题描述】:
import ast # needed to read text as a dictionary
import operator # needed to find term with maximum value
def define_words():
    final_dict={}
    with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt','r', encoding = "utf-8") as dic:
        dante_dict = ast.literal_eval(dic.read())# reads text as a dictionary
        print('the start length was: ', len(dante_dict)) # start length of source dictionary

        key_to_find = max(dante_dict.items(), key=operator.itemgetter(1))[0]
        print('The next word to define is ', key_to_find) # show which word needs defining

        definition = input('Definition ? : ') # prompt for definition
        for key in dante_dict.keys():
            if key == key_to_find:
                final_dict.update({key_to_find:definition})
        dante_dict.pop(key_to_find)             
        print('the end length is : ' ,len(dante_dict)) 
        print(dante_dict) # print source dictionary, modified
        print(final_dict) # print dictionary with newly defined entry

    with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt', 'w', encoding = 'utf-8') as outfile:
        outfile.write(str(dante_dict)) # writes source dictionary minus newly-defined term

    with open('/Users/admin/Desktop/Dante Dictionary/trial_dictionary.txt', 'w', encoding = 'utf-8') as finalfile:
        finalfile.write(str(final_dict)) 

我很抱歉为了回应我所获得的帮助而重新发布了一个类似的问题。不知道如何添加修改。我仍然有这个问题。我的最终字典每次都会被覆盖,而不是附加新定义的术语,所以字典只包含最后一个键:值对。我认为通过使用 dict_name[key] = value,新条目将被附加,而其他条目保持不变。帮助表示赞赏

【问题讨论】:

  • 使用pickle 将字典或任何对象存储到文件中并执行相反的操作。
  • 每次调用函数时都会创建一个 new 字典;您是否希望字典保留先前调用该函数的先前键?
  • 是的,我确实预料到了。请问如何解决这个问题
  • @user1478335 你能给我一个文本文件吗,我想完全重现你的问题。
  • Games Brainiac,谢谢。我怎样才能得到一个文本文件给你?只是我的问题中的文本和编辑,或者有什么方法可以附加文本文件?这是一个小版本:{'amico': 1, "'Segnor": 1, 'volgere': 1, 'spaventate,': 1, "s'avvantaggia": 1, 'livore': 1, 'disposta' : 1, 'pennelli': 1, 'atto': 15, 'Berti': 1, 'atti': 7, 'Gaia': 1, 'alzato,': 1, 'reda': 2, "d'ossa ": 1, 'rede': 1, 'compartir': 1, 'calle': 2, 'dogliose': 1, 'consiglia,': 1, 'piacere,': 2, 'saglia': 1, "l 'ampiezza": 2, "d'Acquasparta,": 1,'solvesi': 1, 'Dopo': 3, 'amico,': 1}

标签: python python-3.x dictionary


【解决方案1】:

您在每个函数调用上创建一个“final_dict”字典,其中包含一个“key_to_find”键。我了解(阅读 cmets)您希望您的函数保留其先前调用的结果,并附加新结果。

函数返回时,函数的命名空间连同其中的所有变量一起被销毁。但是,您可以通过简单地将代码重新排列为两个函数来保存现有字典:

def collectDict():

     # first initialize your final_dict and dante_dict dictionary
     final_dict={}
     with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt','r', encoding = "utf-8") as dic:
             dante_dict = ast.literal_eval(dic.read())# reads text as a dictionary


     # loop as many times you want:
     (dante_dict,final_dict) = define_words(dante_dict,final_dict)    # call the define_words function to update your dictionaries


     # write your dictionaries

     with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt', 'w', encoding = 'utf-8') as outfile:
             outfile.write(str(dante_dict)) # writes source dictionary minus newly-defined term

     with open('/Users/admin/Desktop/Dante Dictionary/trial_dictionary.txt', 'w', encoding = 'utf-8') as finalfile:
             finalfile.write(str(final_dict)) 



 def define_words(dante_dict,final_dict):
      # your already written function without the initialization (first 3 lines) and file writing part

      return(dante_dict,final_dict)  # you return the dictionaries for the other function

这是一个直截了当的解决方案,但请注意classes 是专为您想要做的事情而设计的。

【讨论】:

  • 谢谢。我将在今天晚些时候尝试实现这一点
  • 我已经尝试过您的解决方案,效果很好,除了在我的实现中它仍然覆盖最终字典,因此始终只有一个条目,最新的已被修改。我用泡菜来解决这个问题吗?
  • 我正在做一顿饭。我终于点击了我需要使用'a'而不是'w'!我是个傻孩子!但是即使这样我似乎也无法正确执行:我现在得到 ('word1':'definition1'}{'word2':'definition2'}{'word3':'definition3'}{... }。怎么办我得到 {'word1':'def1', 'word2':'def2',...} ?
  • 您是否从您的 define_words 函数中删除了 final_dict={} 行?
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多