【问题标题】:Storing list into dictionary from excel将列表从excel存储到字典中
【发布时间】:2019-06-23 20:27:39
【问题描述】:

我已将数据从 excel 存储到列表中,但现在我想将其存储到字典中。 here is the excel

在列表中给出这样的输出。

[['Nodeb_IN_New', 107, 'class-default', 'mobility-platinum', 'h1', 7, 'dscp-fc-map', ['ef']], ['', 107, '', 'mobility-gold-new', 'h2', 5, 'dscp-fc-map', ['af41']], ['', 107, '', 'mobility-silver-new', 'l1', 4, 'dscp-fc-map', ['af11', 'af21', 'af31']], ['Nokia_SRAN_S1-MME_X2_IN', 102, '', 'Nokia_SRAN_mobility_platinum', 'h1', 7, 'dscp-fc-map', ['ef', 'nc1']]]

我也想读字典。我已经写了这段代码

def myfun(list):
    list = list
    res=dict()
    qos=None

    for row in list:
        if row[0]=="":
            res[qos]['b']=row[1]
            res[qos]['c']=row[2]
            res[qos]['d']=row[3]
            res[qos]['e']=row[4]
            res[qos]['f']=row[5]
            res[qos]['g']=row[6]
            res[qos]['h']=row[7]

        else:
            qos=row[0]
            res[qos]=dict()
            res[qos]['b']=row[1]
            res[qos]['c']=row[2]
            res[qos]['d']=row[3]
            res[qos]['e']=row[4]
            res[qos]['f']=row[5]
            res[qos]['g']=row[6]
            res[qos]['h']=row[7]

但它给出的输出是这样的。

{'Nodeb_IN_New': {
   'b': 107, 'c': '', 'd': 'mobility-silver-new',
   'e': 'l1', 'f': 4, 'g': 'dscp-fc-map',
   'h': ['af11', 'af21', 'af31']
    }, 
 'Nokia_SRAN_S1-MME_X2_IN': {
   'b': 102, 'c': '', 'd': 'Nokia_SRAN_mobility_platinum', 'e': 'h1', 'f': 7, 'g': 'dscp-fc-map', 'h': ['ef', 'nc1']}}

在“Nodeb_IN_New”下,我想要所有 3 行(来自 excel)。

【问题讨论】:

  • 根据您想要实现的目标,可能值得查看像 pandas 这样可以方便地读取和操作表格数据的库。
  • 我想在 excel 中的“a”列具有一定价值时进行存储,而不是在下一个数据进入“a”列之前存储所有内容。
  • @srish 看看我的代码的结果,我已经把它放在了,如果这就是你要找的,请告诉我

标签: python excel list dictionary jinja2


【解决方案1】:

您的代码不起作用的原因是,当您遍历行并将它们插入目标字典res 时,您还将value 设置为子字典,并且在此子字典中-dictionary,行将始终位于相同的键'b','c','d'等下,换句话说,底部的行将覆盖顶部的行,只剩下第三行Nodeb_IN_New。


另一种方法是将value 设置为一个列表,然后遍历行,如果它们属于同一个qos,则将它们附加到此列表中,代码如下:

# Original excel sheet in a list
raw_list = [
    ['Nodeb_IN_New', 107, 'class-default', 'mobility-platinum', 'h1', 7, 'dscp-fc-map', ['ef']],
    ['', 107, '', 'mobility-gold-new', 'h2', 5, 'dscp-fc-map', ['af41']],
    ['', 107, '', 'mobility-silver-new', 'l1', 4, 'dscp-fc-map', ['af11', 'af21', 'af31']],
    ['Nokia_SRAN_S1-MME_X2_IN', 102, '', 'Nokia_SRAN_mobility_platinum', 'h1', 7, 'dscp-fc-map', ['ef', 'nc1']]
]

result_dict = {}
# title, will be used as key in the result_dict
title = ""

# Loop through the input list
for row in raw_list:
    # If the first value is not empty, replace the title with this new value
    if row[0] != "":
        # update title
        title = row[0]
        # Insert into the dictionary, and give an empty list as a place holder,
        #  later we can append to this list
        result_dict[title] = []
    # At this stage we can append the rest of the input row to the dictionary value
    result_dict[title].append(row[1:])

print("Result dict: ")
for (key, value) in result_dict.items():
    print("Key: {}".format(key))
    for row in value:
        print("    {}".format(row))

这是上面代码的输出:

Key: Nodeb_IN_New
    [107, 'class-default', 'mobility-platinum', 'h1', 7, 'dscp-fc-map', ['ef']]
    [107, '', 'mobility-gold-new', 'h2', 5, 'dscp-fc-map', ['af41']]
    [107, '', 'mobility-silver-new', 'l1', 4, 'dscp-fc-map', ['af11', 'af21', 'af31']]
Key: Nokia_SRAN_S1-MME_X2_IN
    [102, '', 'Nokia_SRAN_mobility_platinum', 'h1', 7, 'dscp-fc-map', ['ef', 'nc1']]

【讨论】:

    【解决方案2】:

    试试这个代码:

    import json
    l=[['Nodeb_IN_New', 107, 'class-default', 'mobility-platinum', 'h1', 7, 'dscp-fc-map', ['ef']], ['', 107, '', 'mobility-gold-new', 'h2', 5, 'dscp-fc-map', ['af41']], ['', 107, '', 'mobility-silver-new', 'l1', 4, 'dscp-fc-map', ['af11', 'af21', 'af31']], ['Nokia_SRAN_S1-MME_X2_IN', 102, '', 'Nokia_SRAN_mobility_platinum', 'h1', 7, 'dscp-fc-map', ['ef', 'nc1']]]
    
    def myfun(list):
        res=dict()
        qos=None
        d={}
        li=[]
        for row in list:
            if row[0]=="":
                res[qos]=dict()
                res[qos]['b']=row[1]
                res[qos]['c']=row[2]
                res[qos]['d']=row[3]
                res[qos]['e']=row[4]
                res[qos]['f']=row[5]
                res[qos]['g']=row[6]
                res[qos]['h']=row[7]
            else:
                qos=row[0]
                res[qos]=dict()
                res[qos]['b']=row[1]
                res[qos]['c']=row[2]
                res[qos]['d']=row[3]
                res[qos]['e']=row[4]
                res[qos]['f']=row[5]
                res[qos]['g']=row[6]
                res[qos]['h']=row[7]
            x = res.keys()
            keylist = []
            keylist.extend(iter(x))
            if keylist[0] in d.keys():
                   d[keylist[0]].append(res[qos])
            else:
                   d[keylist[0]] = []
                   d[keylist[0]].append(res[qos])
        print(d)
        print(json.dumps(d))
    myfun(l)
    

    输出:

    {'Nokia_SRAN_S1-MME_X2_IN': [{'d': 'Nokia_SRAN_mobility_platinum', 'f': 7, 'e': 'h1', 'b': 102, 'c': '', 'h': ['ef', 'nc1'], 'g': 'dscp-fc-map'}], 'Nodeb_IN_New': [{'d': 'mobility-platinum', 'f': 7, 'e': 'h1', 'b': 107, 'c': 'class-default', 'h': ['ef'], 'g': 'dscp-fc-map'}, {'d': 'mobility-gold-new', 'f': 5, 'e': 'h2', 'b': 107, 'c': '', 'h': ['af41'], 'g': 'dscp-fc-map'}, {'d': 'mobility-silver-new', 'f': 4, 'e': 'l1', 'b': 107, 'c': '', 'h': ['af11', 'af21', 'af31'], 'g': 'dscp-fc-map'}]}
    

    导致 json 可读:

        {
      "Nokia_SRAN_S1-MME_X2_IN": [
        {
          "d": "Nokia_SRAN_mobility_platinum",
          "f": 7,
          "e": "h1",
          "b": 102,
          "c": "",
          "h": [
            "ef",
            "nc1"
          ],
          "g": "dscp-fc-map"
        }
      ],
      "Nodeb_IN_New": [
        {
          "d": "mobility-platinum",
          "f": 7,
          "e": "h1",
          "b": 107,
          "c": "class-default",
          "h": [
            "ef"
          ],
          "g": "dscp-fc-map"
        },
        {
          "d": "mobility-gold-new",
          "f": 5,
          "e": "h2",
          "b": 107,
          "c": "",
          "h": [
            "af41"
          ],
          "g": "dscp-fc-map"
        },
        {
          "d": "mobility-silver-new",
          "f": 4,
          "e": "l1",
          "b": 107,
          "c": "",
          "h": [
            "af11",
            "af21",
            "af31"
          ],
          "g": "dscp-fc-map"
        }
      ]
    }
    

    【讨论】:

    • 非常感谢,但它需要“mobility-silver-new”三倍。我想要一个用于“mobility-platinum”、“mobility-gold-new”、“mobility-silver new”。就像“mobility-silver-new”一样,我也想要这两个。
    • { "b": 107, "c": "class-default", "d": "mobility-platinum", "e": "h1", "f": 7, " g”:“dscp-fc-map”,“h”:[“ef”]},{“b”:107,“c”:“”,“d”:“mobility-gold-new”,“e ":"h2","f":5,"g":"dscp-fc-map","h":["af41"] },{"b":107,"c":""," d":"mobility-silver-new","e":"l1","f":4,"g":"dscp-fc-map","h":["af11","af21", "af31" ] } ] }
    • @srish 我已经更新了代码,现在检查一下,抱歉耽搁了
    • 文件“my.py”,第 96 行,在 myfun print(json.dumps(d)) 文件“C:\python3\lib\json_init_.py” ,第 231 行,在转储中返回 default_encoder.encode(obj) 文件“C:\python3\lib\json\encoder.py”,第 199 行,在编码块 = self.iterencode(o, _one_shot=True) 文件中“C:\python3\lib\json\encoder.py”,第 257 行,在 iterencode 返回 _iterencode(o, 0) 文件“C:\python3\lib\json\encoder.py”,第 179 行,默认引发 TypeError (f'Object of type {o.__class_.__name__} ' TypeError: Object of type int64 is not JSON serializable
    • 你提到了这个输出:{'Nokia_SRAN_S1-MME_X2_IN': [{'d': 'Nokia_SRAN_mobility_platinum', 'f': 7, 'e': 'h1', 'b': 102, 'c': '', 'h': ['ef', 'nc1'], 'g': 'dscp-fc-map'}], 'Nodeb_IN_New': [{'d': 'mobility-platinum' , 'f': 7, 'e': 'h1', 'b': 107, 'c': 'class-default', 'h': ['ef'], 'g': 'dscp-fc- map'}, {'d': 'mobility-gold-new', 'f': 5, 'e': 'h2', 'b': 107, 'c': '', 'h': [' af41'], 'g': 'dscp-fc-map'}, {'d': 'mobility-silver-new', 'f': 4, 'e': 'l1', 'b': 107, 'c': '', 'h': ['af11', 'af21', 'af31'], 'g': 'dscp-fc-map'}]} 但是在运行代码时我得到了这个输出:
    猜你喜欢
    • 2019-11-06
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    相关资源
    最近更新 更多