【问题标题】:Python | Add 2 of The Same Keys In A Dict蟒蛇 |在字典中添加 2 个相同的键
【发布时间】:2019-03-14 17:22:45
【问题描述】:

我将如何仅使用 screenshoturl2screenshoturl1 从字典向 JSON 文件添加 2 个相同的键?

这是我现在拥有的代码,它可以工作,但它只添加了第一个 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 中输入的用户输入重新添加它,这样它将删除screenshots 中的占位符之类的所有内容,并且只添加2返回用户在screenshoturl1screenshoturl2 中输入的url,帮助会很好。

谢谢!

【问题讨论】:

  • 你不能,否则它们就不是了,对吧?
  • 您的标题有点令人困惑,所以我想澄清一下:您不能多次向 dict 添加相同的键,因为这使得它不是 python 中的 dict。如果您需要多个具有相同键的值,则可以使用单个键和一个列表作为与该键关联的值
  • 对不起,如果标题令人困惑,我对 python 很陌生,对它了解不多,这就是为什么我在这里发布我的问题,但我仍然对如何去做这个感到困惑跨度>

标签: python json python-3.x


【解决方案1】:

如果我了解您在此处尝试执行的操作,您似乎想一次更新一个或两个 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)

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

【讨论】:

  • 非常感谢,这似乎比以前更好,但现在我将如何添加两个 URL 而不是一个,所以new_urlnew_url2 都有。
  • 你的意思是当脚本完成时,你没有更新的任何截图都会被删除?所以举个例子,如果你只放 1 剩下的 4 会去吗?
  • 这可行,但我想为另一个 url 添加另一个输入字段,并将第一个 new_urlnew_url2 添加到 json 文件中。
  • 我希望 new_urlnew_url2 在 json 文件中是分开的,所以它看起来像这样 {"accessibilityText": "Screenshot","url": "new_url","fullSizeURL": "new_url"},{"accessibilityText": "Screenshot","url": "new_url2","fullSizeURL": "new_url2"}
  • 我已经更新了上面的脚本来剪掉你没有更新的条目。这意味着输出中将有您想要的任意数量。这将支持 2,但它也将支持 3 或 1 等。如果这不是您需要的,那么您可能需要更改它,或者更详细地了解您期望在各种不同场景中看到的输出。祝你好运!
【解决方案2】:

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

from collections import defaultdict

multiValueDict = defaultdict(list)

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

这个输出:

[1, 2]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2013-07-17
    相关资源
    最近更新 更多