【问题标题】:remove square and curly brackets from list从列表中删除方括号和大括号
【发布时间】:2021-04-02 10:31:43
【问题描述】:
CURRENT:
        [
          {key1: [values]},
          {key2: [values]},
        ]
    
    
WHAT I WANT: (no i dont want to print a string)
        {
           key1: [values],
           key2: [values],
        }

我正在从 spark sql 数据帧创建字典,但无法删除括号以获得完美字典。请帮忙

当前代码:

output = []
for row in data.collect():
  key_id = row["KEY"]
  output(key_id) =   {
      "KEY"    :  row["VALUE"],
  }
output= list(output.values())

【问题讨论】:

    标签: python list brackets


    【解决方案1】:

    这样可以正常工作:

    data = [{'key1': ['values']}, {'key2': ['values']},]
    res = {}
    for item in data:
        res.update(item)
    print(res)
    

    输出

    {'key1': ['values'], 'key2': ['values']}
    

    【讨论】:

      【解决方案2】:

      您似乎有字典列表并希望将其转换为字典,所以我们有:

      listOfDicts = [{value1: [values]},{value2: [values]}]
      
      dictYouWant = {key: value for item in listOfDicts for key, value in item.items()}
      

      【讨论】:

        【解决方案3】:

        使用字典理解

        # List of dictionaries
        dict_list =  [
                  {'key1': [1, 2, 3]},
                  {'key2': [4, 5, 6]},
                ]
        
        # Desired result
        new_d = {k: d[k] for d in dict_list for k in d}
        # {'key1': [1, 2, 3], 'key2': [4, 5, 6]}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多