簡體   English   中英

Python | 在字典中添加2個相同的鍵

[英]Python | Add 2 of The Same Keys In A Dict

我如何才能將screenshoturl2的兩個相同的鍵添加到一個dict文件中的screenshoturl2screenshoturl1

這是我現在的代碼,它可以工作,但它只是添加了第一個screenshoturl1而不是screenshoturl2 ,我不知道如何讓它添加它。 在此處查看答復以獲取有關我的主題的更多信息,以及可能有用的信息

    #!/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的占位符之類的所有內容,並且僅將用戶在screenshoturl1screenshoturl2 url2中輸入的網址加回2並且幫助會很好。

謝謝!

您可以將值設為一個集合(例如列表或元組)。 為了方便起見,您可以使用defaultdict。 所以如果你想為一個鍵有兩個值:

from collections import defaultdict

multiValueDict = defaultdict(list)

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

並輸出:

[1, 2]

如果我理解您在此處嘗試做什么,看起來您希望一次更新一個或兩個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)

您可能要查看的其他事情是從函數返回結果,而不是使用全局變量,因為這可能會使大型腳本迅速混淆。

暫無
暫無

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

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