简体   繁体   中英

How to dynamically store values from .json file and compare them with user input in python?

I have.json file like this:

[
{
    "name": {
        "common": "Aruba",
        "official": "Aruba",
        "native": {
            "nld": {
                "official": "Aruba",
                "common": "Aruba"
            },
            "pap": {
                "official": "Aruba",
                "common": "Aruba"
            }
        }
    },
    "tld": [
        ".aw"
    ],
    "cca2": "AW",
    "ccn3": "533",
    "cca3": "ABW",
    "cioc": "ARU",
    "independent": false,
    "status": "officially-assigned",
    "unMember": false,
    "currencies": {
        "AWG": {
            "name": "Aruban florin",
            "symbol": "\u0192"
        }
    },
    "idd": {
        "root": "+2",
        "suffixes": [
            "97"
        ]
    },
    "capital": [
        "Oranjestad"
    ],
    "altSpellings": [
        "AW"
    ],
    "region": "Americas",
    "subregion": "Caribbean",
    "languages": {
        "nld": "Dutch",
        "pap": "Papiamento"
    },
    "translations": {
        "ces": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "deu": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "est": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "fin": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "fra": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "hrv": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "hun": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "ita": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "jpn": {
            "official": "\u30a2\u30eb\u30d0",
            "common": "\u30a2\u30eb\u30d0"
        },
        "kor": {
            "official": "\uc544\ub8e8\ubc14",
            "common": "\uc544\ub8e8\ubc14"
        },
        "nld": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "per": {
            "official": "\u0622\u0631\u0648\u0628\u0627",
            "common": "\u0622\u0631\u0648\u0628\u0627"
        },
        "pol": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "por": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "rus": {
            "official": "\u0410\u0440\u0443\u0431\u0430",
            "common": "\u0410\u0440\u0443\u0431\u0430"
        },
        "slk": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "spa": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "swe": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "urd": {
            "official": "\u0627\u0631\u0648\u0628\u0627",
            "common": "\u0627\u0631\u0648\u0628\u0627"
        },
        "zho": {
            "official": "\u963f\u9c81\u5df4",
            "common": "\u963f\u9c81\u5df4"
        }
    }
},
    
{
    "name": {
        "common": "Afghanistan",
        "official": "Islamic Republic of Afghanistan",
        "native": {
            "prs": {
                "official": "\u062c\u0645\u0647\u0648\u0631\u06cc \u0627\u0633\u0644\u0627\u0645\u06cc \u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646",
                "common": "\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646"
            },
            "pus": {
                "official": "\u062f \u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646 \u0627\u0633\u0644\u0627\u0645\u064a \u062c\u0645\u0647\u0648\u0631\u06cc\u062a",
                "common": "\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646"
            },
            "tuk": {
                "official": "Owganystan Yslam Respublikasy",
                "common": "Owganystan"
            }
        }
    },
    "tld": [
        ".af"
    ],
    "cca2": "AF",
    "ccn3": "004",
    "cca3": "AFG",
    "cioc": "AFG",
    "independent": true,
    "status": "officially-assigned",
    "unMember": true,
    "currencies": {
        "AFN": {
            "name": "Afghan afghani",
            "symbol": "\u060b"
        }
    },
    "idd": {
        "root": "+9",
        "suffixes": [
            "3"
        ]
    },
    "capital": [
        "Kabul"
    ],
    "altSpellings": [
        "AF",
        "Af\u0121\u0101nist\u0101n"
    ],
    "region": "Asia",
    "subregion": "Southern Asia",
    "languages": {
        "prs": "Dari",
        "pus": "Pashto",
        "tuk": "Turkmen"
    },
    "translations": {
        "ces": {
            "official": "Afgh\u00e1nsk\u00e1 isl\u00e1msk\u00e1 republika",
            "common": "Afgh\u00e1nist\u00e1n"
        },
        "cym": {
            "official": "Gweriniaeth Islamaidd Affganistan",
            "common": "Affganistan"
        },
        "deu": {
            "official": "Islamische Republik Afghanistan",
            "common": "Afghanistan"
        },
        "est": {
            "official": "Afganistani Islamivabariik",
            "common": "Afganistan"
        },
        "fin": {
            "official": "Afganistanin islamilainen tasavalta",
            "common": "Afganistan"
        },
        "fra": {
            "official": "R\u00e9publique islamique d'Afghanistan",
            "common": "Afghanistan"
        },
        "hrv": {
            "official": "Islamska Republika Afganistan",
            "common": "Afganistan"
        },
        "hun": {
            "official": "Afganiszt\u00e1ni Iszl\u00e1m K\u00f6zt\u00e1rsas\u00e1g",
            "common": "Afganiszt\u00e1n"
        },
        "ita": {
            "official": "Repubblica islamica dell'Afghanistan",
            "common": "Afghanistan"
        },
        "jpn": {
            "official": "\u30a2\u30d5\u30ac\u30cb\u30b9\u30bf\u30f3\u00b7\u30a4\u30b9\u30e9\u30e0\u5171\u548c\u56fd",
            "common": "\u30a2\u30d5\u30ac\u30cb\u30b9\u30bf\u30f3"
        },
        "kor": {
            "official": "\uc544\ud504\uac00\ub2c8\uc2a4\ud0c4 \uc774\uc2ac\ub78c \uacf5\ud654\uad6d",
            "common": "\uc544\ud504\uac00\ub2c8\uc2a4\ud0c4"
        },
        "nld": {
            "official": "Islamitische Republiek Afghanistan",
            "common": "Afghanistan"
        },
        "per": {
            "official": "\u062c\u0645\u0647\u0648\u0631\u06cc \u0627\u0633\u0644\u0627\u0645\u06cc \u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646",
            "common": "\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646"
        },
        "pol": {
            "official": "Islamska Republika Afganistanu",
            "common": "Afganistan"
        },
        "por": {
            "official": "Rep\u00fablica Isl\u00e2mica do Afeganist\u00e3o",
            "common": "Afeganist\u00e3o"
        },
        "rus": {
            "official": "\u0418\u0441\u043b\u0430\u043c\u0441\u043a\u0430\u044f \u0420\u0435\u0441\u043f\u0443\u0431\u043b\u0438\u043a\u0430 \u0410\u0444\u0433\u0430\u043d\u0438\u0441\u0442\u0430\u043d",
            "common": "\u0410\u0444\u0433\u0430\u043d\u0438\u0441\u0442\u0430\u043d"
        },
        "slk": {
            "official": "Afg\u00e1nsky islamsk\u00fd \u0161t\u00e1t",
            "common": "Afganistan"
        },
        "spa": {
            "official": "Rep\u00fablica Isl\u00e1mica de Afganist\u00e1n",
            "common": "Afganist\u00e1n"
        },
        "swe": {
            "official": "Islamiska republiken Afghanistan",
            "common": "Afghanistan"
        },
        "urd": {
            "official": "\u0627\u0633\u0644\u0627\u0645\u06cc \u062c\u0645\u06c1\u0648\u0631\u06cc\u06c1 \u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646",
            "common": "\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646"
        },
        "zho": {
            "official": "\u963f\u5bcc\u6c57\u4f0a\u65af\u5170\u5171\u548c\u56fd",
            "common": "\u963f\u5bcc\u6c57"
        }
    },
    "latlng": [
        33,
        65
    ],
    "landlocked": true,
    "borders": [
        "IRN",
        "PAK",
        "TKM",
        "UZB",
        "TJK",
        "CHN"
    ],
    "area": 652230,
    "flag": "\ud83c\udde6\ud83c\uddeb"
    
}]

I access it through Javascipt code const data = require('./countries.json'); . What I need from this.json file is translation keys , for example ces , deu , etc. I need to retrieve them dynamically and store in the array called keys . After that, depending on user's input, if input is equal to one of the keys from an array it should print official name of all countries using this key. In my Javascript code I use following methods to do so:

const data = require('./countries.json');
const keys = [];
data.forEach((element) => {
Object.keys(element.translations).forEach((item) => {
keys.push(item);
}) ;
});

/**
*Removes all duplicate translation keys
*@param {1} keys of translation keys
*@return {unique} a unique array of translation keys
*/
function removeDuplicates (keys) { 
const unique = [];
      keys.forEach((element) => {
if (!unique.includes(element)) {
  unique.push(element);
}
});
return unique;
}
const enteredKey = process.argv.slice(2);
console.log('Key is : ', enteredKey);

if (enteredKey.length < 2 && enteredKey !== null && removeDuplicates(keys).includes(enteredKey[0])) {
try {
for (const {translations} of data) {
  const key = translations[enteredKey]?.official;
  if (key) {
    console.log(key);
  }
 }
}

Please note that I am using const key = translations[enteredKey]?.official; because there are a lot of countries and few of them do not have some keys, like cym key is appear in only half of the countries. Without [enteredKey]?.official program will crush because it won't be able to find this key and define it.

Now I need to the same, but with python3 . I have tried:

f = open('./countries.json')
translationKeys = json.load(f)
keys = []
for i in translationKeys[0]["translations"]:
  keys.append(i)
print(keys)
f.close()

but the output was really messy:

['ces']
['ces', 'deu']
['ces', 'deu', 'est']
['ces', 'deu', 'est', 'fin']

Since I am not familiar with python at all, I am curious how to retrieve and store these keys the same way I did that in Javascript and print value of these keys depend on user's input. If user enters deu , program should print every country's official name with deu as a parameter. Kinda like this: 在此处输入图像描述

I will leave a github link for those who wish to see entire project to get more context if needed: https://github.com/TheRadioDept/technical-question

Ok, so after I managed to correct the json you posted, I came up with this code which should get you going.

It reads the json from countries.json and samples it for the "official" country name, plus all the translations into other languages:

import json

with open('countries.json') as f:
    countries = json.load(f)

official_keys = {}
for c in countries:
    official_keys[c['name']['official']] = c['translations']

cc = input('Type country code: ')
for official, keys  in official_keys.items():
    if cc in keys:
        print(official, '=>', keys[cc]["official"])

Typical session:

Type country code: deu
Aruba => Aruba
Islamic Republic of Afghanistan => Islamische Republik Afghanistan

I would suggest you keep the country codes in a dict format. This way you can easily access the underlying data. Note, this only works if all countries have a unique country code. With opening a file you should use the with statement so python closes the file automatically and not damage data.

    with open('./countries.json','r') as f:
        translationKeys = json.load(f)[0]["translations"]

now you can try to match user input

    inp = input('Please provide a country key:')
    if inp in translationKeys.keys():
        print(translationKeys[inp]["official"])
    else:
        print('This country code was not found')

in case you want to list them all you can also loop through the json file. dict.get() will return the corresponding key if it is found, otherwise None.

    inp = input()
    for element in translationKeys:
        if element == inp:
            print(translationKeys[inp]['official'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM