簡體   English   中英

如何刪除嵌套字典中的鍵及其所有值,然后像之前在 Python 中一樣按照“0”、“1”、“2”、“3”的順序更改和排列鍵

[英]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

我希望你們都做得很好。 我在從 json 文件中刪除字典時遇到問題:

我有一個 users.json 有這樣的數據:

{
"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
}

我正在嘗試刪除任何具有所有嵌套數據的鍵,例如“0”鍵,然后按順序排列 json 文件,其中的鍵將按“0”、“1”、“2”、“3”的順序排列他們的嵌套字典。 所以如果去掉“0”鍵,output應該是這樣的:

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

檢查“1”鍵數據是否變為“0”並且所有數據都相似。 我很清楚鍵值不會改變,但我確實相信這個問題有解決方案。 所以請幫幫我:)

我能夠用它的嵌套字典刪除“0”鍵,但從來沒有能夠像以前那樣用排序順序的鍵實現 json。

我的測試代碼:

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)

您可以暫時將字典轉換為列表,刪除特定索引處的項目並以正確的順序再次創建字典。 例如:

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)

印刷:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM