Python |在字典中添加2个相同的键

时间:2019-03-14 17:22:46

标签: python json python-3.x

我如何只用screenshoturl2screenshoturl1从字典将两个相同的键添加到JSON文件?

这是我现在拥有的代码,它可以工作,但是只添加第一个screenshoturl1而不是screenshoturl2,而且我不知道如何添加它。有关我的主题的更多信息以及可能有用的信息,请参见回复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文件:

{
  "tabs": [
    {
      "tabname": "Details",
      "views": [
        {
          "title": "Some Name",
          "useBoldText": true,
          "useBottomMargin": false,
          "class": "DepictionSubheaderView"
        },
        {
          "itemCornerRadius": 6,
          "itemSize": "",
          "screenshots": [
            {
              "accessibilityText": "Screenshot",
              "url": "Screenshot URL 1",
              "fullSizeURL": "Screenshot URL 1"
            },
            {
              "accessibilityText": "Screenshot",
              "url": "Screenshot URL 2",
              "fullSizeURL": "Screenshot URL 2"
            },
            {
              "accessibilityText": "Screenshot",
              "url": "Screenshot URL 3",
              "fullSizeURL": "Screenshot URL 3"
            },
            {
              "accessibilityText": "Screenshot",
              "url": "Screenshot URL 4",
              "fullSizeURL": "Screenshot URL 4"
            },
            {
              "accessibilityText": "Screenshot",
              "url": "Screenshot URL 5",
              "fullSizeURL": "Screenshot URL 5"
            }
          ],
          "ipad": {
            "itemCornerRadius": 9,
            "itemSize": "{320, 550.8266666666667}",
            "screenshots": [
              {
                "accessibilityText": "Screenshot",
                "url": " Screenshot URL?size=640",
                "fullSizeURL": "Screenshot URL"
              }
            ],
            "class": "DepictionScreenshotView"
          },
          "class": "DepictionScreenshotsView"
        },
        {
          "markdown": " Description",
          "useSpacing": true,
          "class": "DepictionMarkdownView"
        },
        {
          "class": "DepictionSeparatorView"
        },
        {
          "title": "Known Issues",
          "class": "DepictionHeaderView"
        },
        {
          "markdown": "None",
          "useSpacing": true,
          "class": "DepictionMarkdownView"
        },
        {
          "class": "DepictionSeparatorView"
        },
        {
          "title": "Latest Version",
          "class": "DepictionHeaderView"
        },
        {
          "title": "1.0",
          "text": "Latest Version Number",
          "class": "DepictionTableTextView"
        },
        {
          "title": "Released",
          "text": "3/10/19",
          "class": "DepictionTableTextView"
        },
        {
          "title": "Price",
          "text": "Free",
          "class": "DepictionTableTextView"
        },
        {
          "title": "Developer",
          "text": "TestDev",
          "class": "DepictionTableTextView"
        },
        {
          "title": "Contact Support",
          "action": "",
          "class": "DepictionTableButtonView"
        },
        {
          "spacing": 16,
          "class": "DepictionSpacerView"
        },
        {
          "spacing": 20,
          "class": "DepictionSpacerView"
        }
      ],
      "class": "DepictionStackView"
    },
    {
      "tabname": "Changelog",
      "views": [
        {
          "title": "1.0",
          "useBoldText": true,
          "useBottomMargin": true,
          "class": "DepictionSubheaderView"
        },
        {
          "markdown": "\t\n\u2022 Initial Release",
          "useSpacing": false,
          "class": "DepictionMarkdownView"
        },
        {
          "markdown": "<small style=\"color: #999; margin-top: -8px;\">Released 3/10/2019</small>",
          "useRawFormat": true,
          "class": "DepictionMarkdownView"
        }
      ],
      "class": "DepictionStackView"
    }
  ],
  "class": "DepictionTabView"
}

我希望它删除screenshots中的所有内容,并使用他们在screenshoturl1screenshoturl2中输入的用户输入重新添加,因此它将删除诸如{中的占位符{1}},并且仅将用户在screenshotsscreenshoturl1中输入的URL加2即可,帮助会很不错。

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以将值设为一个集合(例如列表或元组)。为了增加便利,您可以使用defaultdict。因此,如果您想要一个键具有两个值:

from collections import defaultdict

multiValueDict = defaultdict(list)

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

这将输出:

[1, 2]

答案 1 :(得分:0)

如果我了解您要在此处进行的操作,则您似乎想一次更新一个或两个URL。

您可以做的是一次浏览每个屏幕截图项目,然后更新或停止。这样比较容易,如果需要,还可以更新所有它们。这也意味着我们不必问要先做多少事(只要再没有其他东西就停下来)。

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)

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