Python Forum
saving a dictionary as json file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
saving a dictionary as json file
#1
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.
Reply
#2
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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.
Reply
#4
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).
Reply
#5
(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.... :-)
Reply
#6
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'
Reply
#7
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 :-).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  encrypt data in json file help jacksfrustration 1 68 Yesterday, 05:16 PM
Last Post: deanhystad
  parse json field from csv file lebossejames 4 669 Nov-14-2023, 11:34 PM
Last Post: snippsat
  Python Script to convert Json to CSV file chvsnarayana 8 2,346 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  Loop through json file and reset values [SOLVED] AlphaInc 2 1,962 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,174 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  validate large json file with millions of records in batches herobpv 3 1,222 Dec-10-2022, 10:36 PM
Last Post: bowlofred
  Saving the times a script is run to a file or ... 3Pinter 7 1,322 Oct-19-2022, 05:38 PM
Last Post: 3Pinter
  Code Assistance needed in saving the file MithunT 0 784 Oct-09-2022, 03:50 PM
Last Post: MithunT
  Saving the print result in a text file Calli 8 1,700 Sep-25-2022, 06:38 PM
Last Post: snippsat
  Writing to json file ebolisa 1 970 Jul-17-2022, 04:51 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020