【问题标题】:List of data and an empty dictionary keys - Is there a way to assign the data sequentially to the dictionary key数据列表和空字典键 - 有没有办法将数据顺序分配给字典键
【发布时间】:2021-07-27 23:07:31
【问题描述】:

我的字典内容如下

contentDict = {
            "Prefecture": "",
            "Total List Number": "",
            "Title": "",
            "Event Validity": "",
            "Available Period": "",
            "Available StartDate": "",
            "End Date": "",
            "Last Updated": "",
            "mainText": "",
            "Location Tag": "",
            "Event Tag": "",
            "Main Image URL": "",
            "innerWebSiteURL": "",
            "ListLink": ""
        }

和一个相同长度的内容列表。

有没有办法将列表的每个内容顺序分配给字典

我尝试使用 zip() 但失败了

字典需要按指定的顺序排序,因为我想按照提供的顺序将它添加到 mysql 数据库中。..

最终的目标是使用 to_sql() 方法将字典放入 MySQL 数据库中

我最初编码时没有考虑 MySQL,后来被告知使用 ORM to_SQL 方法来传输数据..

任何提示或指南将不胜感激

【问题讨论】:

    标签: python dictionary syntax sqlalchemy orm


    【解决方案1】:

    好吧,假设您的列表是 contentList

    contentList = [i for i in range(14)]
    

    一件事是循环键:

    for i,k in enumerate(contentDict):
        contentDict[k] = contentList[i] 
    

    或者'pythonically':

    contentDict = {k:contentList[i] for i,k in enumerate(contentDict)}
    

    【讨论】:

    • 感谢您的信息,非常感谢。我只是有点好奇。你如何学习pythonical表达式。我觉得它们很漂亮......表达代码的最短方式......但我似乎从未在任何地方找到它们可以学习......或者只是重复的经验
    • 另一个pythonic选项:newDict = dict(zip(contentDict.keys(), contentList))
    猜你喜欢
    • 2021-06-03
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2021-12-09
    • 2021-06-04
    相关资源
    最近更新 更多