简体   繁体   中英

How to remove key and all its values in a nested dictionary then change and arrange keys in this "0","1","2","3" order like it was before in Python

I hope you all are doing well. I am having a problem with removing a dictionary from a json file:

I have a users.json which has data like this:

{
"0": {
    "course": "fjjc",
    "password": "fhjf",
    "username": "1800101253"
},
"1": {
    "course": "fjjc",
    "password": "fhjf",
    "username": "1800101254"
},
"2": {
    "course": "fjjc",
    "password": "fhjf",
    "username": "1800101257"
},
"3": {
    "course": "fjjc",
    "password": "fhjf",
    "username": "1800101258"
},
    "Total": 4
}

I am trying to remove any key with all its nested data like for example "0" key and then arrange the json file in order which will have keys in this order "0","1","2","3" with their nested dictionary. So if "0" key is removed, the output should be like this:

{
"0": {
    "course": "fjjc",
    "password": "fhjf",
    "username": "1800101254"
},
"1": {
    "course": "fjjc",
    "password": "fhjf",
    "username": "1800101257"
},
"2": {
    "course": "fjjc",
    "password": "fhjf",
    "username": "1800101258"
},
    "Total": 3
}

Check that "1" key data came to "0" and similar for all. I am well aware that keys values doesn't change, but I do believe there is a solution for this problem. So help me out please:)

I was able to remove the "0" key with its nested dictionary, but was never able to implement the json with keys in sorted order like it was before.

My Test Code:

with open("users.json") as jsonFile3:      #Reading users details into users.json
        users = json.load(jsonFile3)
        total = users["Total"]
        for i in range(total):
            if users[f"{i}"]["username"] == f"{username}":
                del users[f"{i}"]
                pos=i
                removed = True
        if removed == True:
            for i in range(pos,total):
                if f"{i}" in users:
                    if i==0:
                        continue
                    else:
                        users[f"{key-1}"] = users.pop(f"{key}")

        users["Total"] = total-1
        with open("users.json",'w') as jsonFile4:
            json.dump(users,jsonFile4, indent=4, sort_keys=True)

You can temporarily convert the dictionary to list, remove the item at specific index and create dictionary again in correct order. For example:

dct = {
    "0": {"course": "fjjc", "password": "fhjf", "username": "1800101253"},
    "1": {"course": "fjjc", "password": "fhjf", "username": "1800101254"},
    "2": {"course": "fjjc", "password": "fhjf", "username": "1800101257"},
    "3": {"course": "fjjc", "password": "fhjf", "username": "1800101258"},
    "Total": 4,
}

to_remove = 0

lst = [dct[str(v)] for v in range(dct["Total"])]
lst.pop(to_remove)
dct = {str(i): v for i, v in enumerate(lst)}
dct["Total"] = len(lst)

print(dct)

Prints:

{'0': {'course': 'fjjc', 'password': 'fhjf', 'username': '1800101254'}, 
 '1': {'course': 'fjjc', 'password': 'fhjf', 'username': '1800101257'}, 
 '2': {'course': 'fjjc', 'password': 'fhjf', 'username': '1800101258'},  
 'Total': 3}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM