从列表中删除方括号和大括号

问题描述

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())

解决方法

这会正常工作:

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

输出

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

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

listOfDicts = [{value1: [values]},{value2: [values]}]

dictYouWant = {key: value for item in listOfDicts for key,value in item.items()}
,

使用字典理解

# 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,3],'key2': [4,6]}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...