Create a JSON file from a dictionary of lists

I am using a dictionary of lists to create a JSON file.

My code is:


     new_dict={} #to stop the JSON file 

    #three lists, the first is supposed to by the key

    name=['suzen','lilly','sara']
    hobbies=['chess','reading','dancing']
    age=[13,14,15]

   #the other two lists are the values of my dictionary.
    dict_values={'hobbies':hobbies,'age':age}
   
    #trying to assign the name list to each value in a dictionary 
    new_dict[name]=dict_values

    with open('student.json','w') as student:
        student.write(str(new_dict))

I would like the final output to be:

{'suzan':{'age':13,'hobbies':chess},
'lilly':{'age':15,'hobbies':reading},
'Sara':{'age':14,'hobbies':dance}}

{key:{key:value, key:value}, key:{key:value, key:value}}

My problem is I can’t assign each element of name list as the key to the corresponding elements in the other lists.

I also tried this


   #converting the name list to a dictionary to use the list items as key
   name=['suzen','lilly','sara']
   namedict={i: i for i in name}
   namedict=dict.fromkeys(name)

  #for loop to iterate through the dictionary
  for i in namedict.keys():
        namedict[i]=dict_values
print(namedict)

I get this output

{‘suzen’: {‘hobbies’: [‘chess’, ‘reading’, ‘dancing’], ‘age’: [13, 14, 15]}, ‘lilly’: {‘hobbies’: [‘chess’, ‘reading’, ‘dancing’], ‘age’: [13, 14, 15]}, ‘sara’: {‘hobbies’: [‘chess’, ‘reading’, ‘dancing’], ‘age’: [13, 14, 15]}}

I would like to assign the first element of each list to the firs name ‘suzan’, and so on.

This task must be accomplished through the use of dictionaries. So I can’t use json or pandas for that.

Hello, welcome to the forum :slight_smile:

You can simply use a for loop (for i in range(len(name))). The key would be name[i], hobby - hobbies[i], age - age[i].

2 Likes

Irrelevant to what you’re trying to solve, but a thought: is the name really so special it should be treated differently from the other attributes?
Could also be:

[{"name": "suzan", "age": 13, "hobbies": "chess"},
 {"name": "lilly", "age": 15, "hobbies": "reading"},
 {"name": "Sara", "age": 14, "hobbies": "dance"}]

You might even have two persons that share a name. It’s pretty likely for a group roughly the size of a classroom.

4 Likes

this returns

{0: ‘chess’, 1: ‘reading’, 2: ‘dancing’}

this is for an assignment I have. I can’t change the output structure.

name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]

for i in range(len(name)):
    print(name[i], hobbies[i], age[i])

Inside this for loop you have all the information you need to correctly build the dictionary.

2 Likes

Thank you factoradic.
But I know how to write such loops. My question is about the final Json format.

Maybe if you played around with a dict for a simpler scenario.

GIven an empty dict, how would you add the keyvaluepairs 'a': 1, 'b':2 to it? That’s entirely straightforward, is it not? And making your dict is… the same thing.

2 Likes

I am trying to find a way to assign a key/value pair to a key.

the key/value pair coming from the age and hobbies lists

and the key from the name list.

Assuming that you know how to add 'a': 1
What’s the key, and what is the value there?
The key is ‘a’, the value is 1.

Take a look at one of your entries. What is the key? What is the value? Create them, and then add them to the dict.

Here’s one of your entries:

'suzen': {'hobbies': 'chess', 'age': 13}

What value is the key?
What value is the value?

If you look at the value, it is another dict/json object.
It’s the same thing all over again. It’s not different. Do the same thing.

So if you can add a key-value pair (‘a’, 1), then, that’s all you would need to do here as well. You’re not missing any information.

3 Likes

I am trying to create a Json file using a dictionary of lists.

My key is the name, followed by key/value pair within that key. so my final Json file would like like the sample I attached in my post.

My problem is with extracting the corresponding elements from the lists I have as values.

@factoradic showed you how to do that

I copied the wrong entry, I meant this:

{'suzen': {'hobbies': 'chess', 'age': 13}}

Which is obtained through repeated key-value insertions.

2 Likes

Oh and note that python’s string representations of dicts are not valid json. json strings are double quoted, you’ll get single quoted strings if you print a python dict. There are some other differences too.

3 Likes

okay, thank you for your help and time.

when I follow that method I get a different output from the one I want.

new_dict={}

for i in range(len(name)):
    new_dict[name[i]]=hobbies[i],age[i]

I get this

{'suzen': ('chess', 13), 'lilly': ('reading', 14), 'sara': ('dancing', 15)}

Nobody suggested that.

But if you look at an entry for one person…
Figure out what the key is. Store that in a variable.
Then figure out what the value is. The value is another dict, so you’d build that dict.

Then, when you have both the key and the value, you can add it to your outermost dict.

@factoradic’s loop provides all the values that an entry needs.
And the entry is built with a single operation repeated over and over: inserting a key-value pair. Where should it be inserted? With what key? With what value? Repeat.

1 Like

I have one list which is name. This is where my keys come from.

Then I have a dictionary that contains {key:value} the value is a list. I can’t extract the element that corresponds to the name.

If I add the name list as my key, and the dictionary as my value I get an error.

name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]

dict_values={'hobbies':hobbies,'age':age}

new_dict[name]=dict_values

unhashable type: 'list'

If you start out with that loop then there’s no more extracting to do.
You already have the individual values, what would extract beyond these?

first iteration:  'suzen' 'chess'   13
second iteration: 'lilly' 'reading' 14
third iteration:  'sara'  'dancing' 15

There’s no such key. Which key were you after? Use that one.

1 Like

It is possible to extract the values. But I can’t arrange them together in the shape of my final format. This is what I am trying to accomplish with the for loop

2 Likes

And you’d do that by looking at which key-value pairs are to be inserted. Which is the key? Which is the value. Insert. You have all the keys already, the values need to be built before you can insert them. The values are just dicts, so it’s the exact same thing, nothing new.

Open up a python repl and start with an empty dict. Start inserting things into it.

$ python
>>> data = {}
>>> 
1 Like