-4
CURRENT:
        [
          {key1: [values]},
          {key2: [values]},
        ]
    
    
WHAT I WANT: (no i dont want to print a string)
        {
           key1: [values],
           key2: [values],
        }

am creating a dictionary from a spark sql dataframe and unable to remove the brackets for a perfect dictionary. Please help

CURRENT code :

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

3 Answers3

0

This will work fine:

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

Output

{'key1': ['values'], 'key2': ['values']}
Cute Panda
  • 1,468
  • 1
  • 6
  • 11
0

It seems you have list of dicts and want to convert it to a dict so we have:

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

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

Using dictionary comprehension

# 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]}
DarrylG
  • 16,732
  • 2
  • 17
  • 23