如果尚未创建字典,则创建一个字典,然后将其追加 [英] Create a dict if its not already created and then append to it

查看:56
本文介绍了如果尚未创建字典,则创建一个字典,然后将其追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件列表,我需要在其中选择几行包含CommonChar的行,并致力于创建字典.我感兴趣的文件中的行如下所示:

I have a list of files in which I need to select few lines which has CommonChar in them and work on creating a dictionary. The lines in a file which I am interested in look like these:

CommonChar uniqueName field value 

CommonChar uniqueName field1 value1

CommonChar uniqueName1 field value

CommonChar uniqueName1 field1 value1 

因此,我想要一个最终的字典,该字典将存储以uniqueName和键值对命名的内部字典为(field:value,field1:value1)

So with this I would want a final dictionary which will store internal dictionaries named on uniqueName and key value pairs as (field: value, field1:value1)

这样,我将拥有一个基于uniqueName和键值对的内部dict的主字典.

This way I will have a main dict with internal dict based on uniqueName and key value pairs.

最终输出应如下所示:

mainDic={'uniqueName': {'field':'value', 'field1':value1, 'field2':value2},
          'uniqueName1':{'field':'value', 'field1':value1, 'field2':value2} }

推荐答案

"Apple"和"Grapes"由于是字符串而不能创建为字典.我假设您的程序中有一些流程像这样:

'Apple' and 'Grapes' can't be created as dictionaries since they are strings. I'm assuming you have a flow in your program that goes something like this:

  1. 创建一个包含有关苹果信息的字典
  2. 将该字典分配给变量apple
  3. 检查这个刚刚创建的字典是否已经在mainDict中
  4. 如果不是,请将其添加到键"Apple"下的mainDict值中

  1. create a dictionary containing information about apples
  2. assign that dictionary to the variable apple
  3. check if this just created dictionary is already in mainDict
  4. if not, add it to the values of mainDict under the key 'Apple'

mainDict= {'Grapes':{'Arabian':'25','Indian':'20'} }
apple = {'American':'16', 'Mexican':10, 'Chinese':5}

if apple not in mainDict.values():
    mainDict['Apple'] = apple

mainDict

输出:

{'Apple': {'American': '16', 'Chinese': 5, 'Mexican': 10},
 'Grapes': {'Arabian': '25', 'Indian': '20'}}

我认为您遇到的问题是,没有通用的方式来获取名称对象作为字符串.字典没有 name 属性.请参考以下答案:如何获取Python中对象的名称?

The problem I think you have, is that there's no general way to get the name of an object as a string. Dicts don't have a name attribute. Refer to these answers: How can I get the name of an object in Python?

这篇关于如果尚未创建字典,则创建一个字典,然后将其追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆