Python Forum
saving a dictionary as json file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: saving a dictionary as json file (/thread-27430.html)



saving a dictionary as json file - vinay_py - Jun-06-2020

import json
with open("users.json") as datafile: 
    data = json.load(datafile)       # loaded json file data into python string
data_with_id = []                    #For addinng data with new id numbers to be used for grouping

def newdict():                       #function for adding items to new empty dictionary
    n=1000                           # variable for adding data with ID numbers in new dictionary
    for items in data:
        data_with_id.append({"idnum":n,"name":items["first_name"],"gender":items["gender"],"email":items["email"]})
        n = n+1

newdict ()
print("\nUsers with alloted ID are as below--\n")
for users in data_with_id:
   print("ID number",":" ,users["idnum"],"Name",":",users["name"],"gender",":",users["gender"],"E-Mail address",":",users["email"])
       
id_num_list = []                     #For only ID numbers added as n in newdict
for users in data_with_id:
    id_num_list.append(str(users["idnum"]))
print("\n ID numbers are : ",id_num_list)

def create_new_group(selected_ids_list):
    new_group = []
    for n in data_with_id:
        for m in selected_ids_list:
            if m in str(n["idnum"]):
                new_group.append({n["name"],n["gender"],n["email"]})
    with open("write_it.json","w") as writefile:
        writefile.write(json.dumps(new_group))
    print("\n File is saved")
    
def selection_for_grouping():    
    x = input("\nselect ID numbers by comma seperated from list to create a group : ")
    selected_ids_list = x.split(",")
    print("\nselected IDs are : ",selected_ids_list)
    for selected in selected_ids_list:
        if selected in id_num_list:
            continue
        if selected not in id_num_list:
            print("ID does not exists :",selected)
    create_new_group(selected_ids_list)

selection_for_grouping()
print("Great its done")
Error:
Traceback (most recent call last): File "C:\Users\Vinay.Prajapati\Desktop\Python Programs\reading json file - users - basic.py", line 51, in <module> selection_for_grouping() File "C:\Users\Vinay.Prajapati\Desktop\Python Programs\reading json file - users - basic.py", line 49, in selection_for_grouping create_new_group(selected_ids_list) File "C:\Users\Vinay.Prajapati\Desktop\Python Programs\reading json file - users - basic.py", line 36, in create_new_group writefile.write(json.dumps(new_group)) File "C:\Python\Python Program\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "C:\Python\Python Program\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Python\Python Program\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Python\Python Program\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type set is not JSON serializable
The issue is with saving the new_group (selected ids by user) is not being saved in json showing error as above. the reason is its type is set instead of dictionary. so i need help what i can do here to solve this.

I also want it to save as group_name as per the name input by user string

Please note I am a bigginer, learning python and doing practice project by self.
I have recently learnt basics of python.



RE: saving a dictionary as json file - buran - Jun-06-2020

what is the idea of this {n["name"],n["gender"],n["email"]}? why do you want to append a set? I guess there is some misunderstanding on your part to different container types - list, dict, set, tuple, etc.


RE: saving a dictionary as json file - vinay_py - Jun-06-2020

Please note description -

1. I am reading through a .json file dictinary. takinng those users data and created a new dictionary along with allotment of a ID numbers to all of the items (userdata) of dictionary.

2. Displaying the data along with ID numbers.
3. Asking for users to select some ID numbers for grouping.
Quote:4. On the basis of selection by user I have created a new List/Dict for selected IDs user data.
Help me here i i can create a dictionary in any other ways. to quickly save it as json.
Quote:5. next i want to ask the group name from user for giving this json file name as mentioned by user.
also need help here.

(Jun-06-2020, 04:12 PM)buran Wrote: what is the idea of this {n["name"],n["gender"],n["email"]}? why do you want to append a set? I guess there is some misunderstanding on your part to different container types - list, dict, set, tuple, etc.
Hi Buran,

Thanks for your very fast response.

please elobrate for my better understanding. I am at the bigginers level. this is my first work. I am trying all the learnt things for the first time. If you explain me i'll not make any mistake again.


RE: saving a dictionary as json file - deanhystad - Jun-06-2020

A set is a container type in python, like list, tuple and dictionary. This is Python for making a set
myset={'a', 'b', 'c'}
A set is like a list, but unlike a list there can only be one of each element. This is a valid list in Python
mylist = ['a', 'b', 'c', 'a']
But if you converted the list to a set, the resulting set would only contain 'a' once.

"set" is not one of the things that json can serialize (load or dump). The code buran pointed out makes a set. If you use square brackets to make a list instead of a set, json would work. If you want to add entries to the dictionary you need to use the proper syntax for doing that (dictionary[key] = value).


RE: saving a dictionary as json file - vinay_py - Jun-06-2020

(Jun-06-2020, 04:42 PM)deanhystad Wrote: A set is a container type in python, like list, tuple and dictionary. This is Python for making a set
myset={'a', 'b', 'c'}
A set is like a list, but unlike a list there can only be one of each element. This is a valid list in Python
mylist = ['a', 'b', 'c', 'a']
But if you converted the list to a set, the resulting set would only contain 'a' once.

"set" is not one of the things that json can serialize (load or dump). The code buran pointed out makes a set. If you use square brackets to make a list instead of a set, json would work. If you want to add entries to the dictionary you need to use the proper syntax for doing that (dictionary[key] = value).

Wonderfull..... Thanks a lot deanhystad. I got it now. I tried it in my code by removing {} also. I understood your point.
but now it is saving a list in new json file. and i want it the same as the file its reading from that is key:value pair way. what couuld i do next ?


agains thanks a lot for your quick replies.... :-)


RE: saving a dictionary as json file - deanhystad - Jun-06-2020

The syntax for adding entries to a dictionary is dictionary[key] = value

mydict['nickname'] = 'Grumpy' would add 'nickname' to 'mydict' and assign it the value 'Grumpy'


RE: saving a dictionary as json file - vinay_py - Jun-06-2020

saw some videos as per reason of error given by you both. now the code is correct and working. Thanks a lot to both of you for lightfastning replies :-).