2

I am seeking to use a Python dictionary with key: array pairs as a basis for constructing a database table. The dictionary is constructed as follows:


schema = {'names': ['Field1', 'Field2', 'Field3'], 'type': ['STRING', 'STRING', 'INTEGER']}

The resulting JSON data structure that I am seeking to produce would be, for lack of better phrasing, an array of JSON elements, as below:

[
    {
        'names': 'Field1',
        'type': 'STRING'
    },
    {
        'names': 'Field2',
        'type': 'STRING'
    },
    {
        'names': 'Field3',
        'type': 'INTEGER'
    }
]

I have used the json module and attempted to do this as follows:

import json
schema = {'names': ['Field1', 'Field2', 'Field3'], 'type': ['STRING', 'STRING', 'INTEGER']}
json.dumps(schema)

However, it gives me:

'{"names": ["Field1", "Field2", "Field3"], "type": ["STRING", "STRING", "INTEGER"]}'

I can do this by constructing the string using {}.format(..) but I wanted to see if there was a more efficient manner. I have searched through numerous threads but most threads seem to do the opposite of what I am seeking to do.

Any pointers?

Cheers.

3 Answers 3

1

You could zip your names and types arrays together and pass that to a list comprehension to make and array of dictionaries. Then dump to JSON:

import json
schema = {'names': ['Field1', 'Field2', 'Field3'], 'type': ['STRING', 'STRING', 'INTEGER']}

# assuming values is just those two lists otherwise spell out explicitly:
l = [{"names":name, "type":field} for name, field in zip(*schema.values())] 

json.dumps(l)

Result:

'[{"names": "Field1", "type": "STRING"}, {"names": "Field2", "type": "STRING"}, {"names": "Field3", "type": "INTEGER"}]'
Sign up to request clarification or add additional context in comments.

Comments

0

Use zip() to get name/type pairs and build a list of small dictionaries:

schema = {'names': ['Field1', 'Field2', 'Field3'], 'type': ['STRING', 'STRING', 'INTEGER']}

data = []
for n,t in zip(schema['names'], schema['type']):
    data.append({'name': n, 'type': t})

Comments

0

By directly accessing the dictionary in a for loop, you can match each element of names and type:

schema = {'names': ['Field1', 'Field2', 'Field3'], 'type': ['STRING', 'STRING', 
'INTEGER']}
output = []
names = schema["names"]
type = schema["type"]

for i in range(len(schema["names"])):
    output.append({"names": names[i], "type": type[i]})

print(output)

Output:

[{'names': 'Field1', 'type': 'STRING'}, {'names': 'Field2', 'type': 'STRING'}, {'names': 'Field3', 'type': 'INTEGER'}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.