Python Add 2 of The Same Keys In A Di

2024-09-29 22:35:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我该如何从dict向JSON文件添加2个相同的键,只使用screenshoturl2和{}?在

这是我现在的代码,它可以工作,但它只添加了第一个screenshoturl1,而不是{},我不知道如何让它添加它。请参阅回复here以获取关于我的主题的更多和可能有用的信息

    #!/usr/bin/env python3
import os
import sys
import json
import fileinput

def NumberofScreenshots():
    global numberofscreenshots
    while True:
        try:
            numberofscreenshots = input("Number of Screenshots?: ")
            if numberofscreenshots == '':
                print("Please enter how much screenshots to include.")
                continue
            elif numberofscreenshots.isalpha():
                print("Please enter a number not a string.")
                continue
            else:
                break
        except ValueError:
            break
def ScreenshotURL():
    global screenshoturl1, screenshoturl2
    if numberofscreenshots == "1":
        screenshoturl1 = input("Screenshot URL: ")
    elif numberofscreenshots == "2":
        screenshoturl1 = input("Screenshot URL: ")
        screenshoturl2 = input("Screenshot URL: ")
    else:
        pass
def NumberofScreenshots1():
    if numberofscreenshots == "1":
        with open('path/to/json/file','r') as f:
            data = json.loads(f.read())

        data['tabs'][0]['views'][1]['screenshots'][0]

        data['tabs'][0]['views'][1]['screenshots']  =  data['tabs'][0]['views'][1]['screenshots'][0]

        data['tabs'][0]['views'][1]['screenshots'] = {"accessibilityText": "Screenshot","url": screenshoturl1,"fullSizeURL": screenshoturl1}

        with open('path/to/json/file', 'w') as f:
            f.write(json.dumps(data))
    else:
        print("Try again.")
def NumberofScreenshots2():
    global data
    if numberofscreenshots == "2":
        with open('path/to/json/file','r') as f:
            data = json.loads(f.read())

        data['tabs'][0]['views'][1]['screenshots'][0]
        print(data)

        data['tabs'][0]['views'][1]['screenshots'] = data['tabs'][0]['views'][1]['screenshots'][0]
        print(data)


        data['tabs'][0]['views'][1]['screenshots'].update({"accessibilityText": "Screenshot","url": screenshoturl1,"fullSizeURL": screenshoturl1, "accessibilityText": "Screenshot","url": screenshoturl2,"fullSizeURL": screenshoturl2})
        print(data)

        with open('path/to/json/file', 'w') as f:
            f.write(json.dumps(data))
    else:
        print("Try again.")


print("Pick Template:")
print("1. Default")
template = input("Template Name/Number: ")

if (template == "1"):
    NumberofScreenshots()
    ScreenshotURL()

    NumberofScreenshots1()
    NumberofScreenshots2()

# Show the user a error if they enter a number for a template that can't be found.
else:
    print("The template you are looking for can not be found!")

我们正在查看名为NumberofScreenshots2的函数

JSON文件:

^{2}$

我希望它删除screenshots中的所有内容,并使用用户在screenshoturl1screenshoturl2中输入的用户输入重新添加,这样它将删除screenshots中的占位符一样的所有内容,只添加2个用户在screenshoturl1和{}中输入的url,帮助会很好。在

谢谢!在


Tags: toimportjsoninputdataifelseviews
2条回答

您可以将值设置为集合(如列表或元组)。为了方便起见,可以使用defaultdict。因此,如果您希望一个键有两个值:

from collections import defaultdict

multiValueDict = defaultdict(list)

multiValueDict[1].append(1)
multiValueDict[1].append(2)
print(multiValueDict[1])

这个输出:

^{pr2}$

如果我理解你在这里想做什么,看起来你想更新一个或两个网址,一次一个。在

你能做的就是检查每个截图项目,一次一个,要么更新要么停止。这更容易,而且如果你想更新所有的文件。这也意味着我们不必预先询问要做多少(当我们没有更多的东西时,我们就停下来)。在

import json

# Load the data
file_name = 'path/to/json/file'
with open(file_name) as fh:
    full_data = json.load(fh)

# Dig into the data to find the screenshots
screen_shots = full_data['tabs'][0]['views'][1]['screenshots']

# Loop over each screen shot, updating each one
for number, screen_shot in enumerate(screen_shots):
    print("Screenshot", number)
    print('\tCurrent data:', screen_shot)

    new_url = input(
        "\tPlease enter new URL (leave empty and press return to stop): "
    ).strip()

    if new_url:
        # Updating the data here will also update the 'full_data' object
        # as we are just referencing a part of it, not making copies
        screen_shot.update({"url": new_url, "fullSizeURL": new_url})
    else:
        print("\tAll done!")
        break

# Remove all entries which we did not update
screen_shots = screen_shots[:number]

# Save the data
with open(file_name, 'w') as fh:
    json.dump(full_data, fh, indent=4)

您可能还需要研究从函数返回结果,而不是使用全局变量,因为这会很快与更大的脚本混淆。在

相关问题 更多 >

    热门问题