Learn how to retrieve values from a .json file in real-time and then perform comparisons with user input using Python

I have a JSON file structured like this:

[
{
    "name": {
        "common": "Aruba",
        "official": "Aruba",
        "native": {
            "nld": {
                "official": "Aruba",
                "common": "Aruba"
            },
            "pap": {
                "official": "Aruba",
                "common": "Aruba"
            }
        }
    },
    "tld": [
        ".aw"
    ],
    ...
}]

Using JavaScript, I access this data with the code

const data = require('./countries.json');
. My goal is to extract the translation keys, such as ces, deu, etc., dynamically and store them in an array called keys. Then based on user input, if it matches one of the keys, the program should print the official name of all countries using that key.

In my JavaScript, I use the following methods to achieve this:


// JavaScript Code
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;
}
...

To achieve the same functionality in Python, you can use the following code snippet:


# Python Code
import json

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

This Python code will retrieve and store the keys similar to the JavaScript implementation. You can then enhance it to print the values based on user input, just like how it's done in the JavaScript version.

If you need more context or want to explore the full project, you can check out the GitHub link: https://github.com/TheRadioDept/technical-question

Answer №1

After successfully fixing the json you provided, here is a modified code snippet that should help solve your issue.

This code reads data from the countries.json file and retrieves the official country name along with translations in various languages:

import json

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

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

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

Example interaction:

Enter country code: fra
Canada => Canada
German Democratic Republic => Deutsche Demokratische Republik

Answer №2

To efficiently manage country codes, storing them in a dictionary format is recommended. This allows for easy access to the data. It's important to note that this method works best when each country has a unique code. When opening a file, it's good practice to use the 'with' statement in Python to ensure automatic closure of the file and prevent any potential data corruption.

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

Now you can compare user input against the stored country codes:

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

If you wish to display all country codes, you can iterate through the JSON file by utilizing dict.get() which will return the corresponding key if found, or None:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate a JSON array containing objects consisting of a combination of string and boolean values

My goal is to generate a list containing objects with names and boolean values by utilizing AJAX. This process is initiated in the following manner: $('.si-accordion').click(function () { $(this).siblings('.accordion_tab&apo ...

Having difficulty initializing jQuery DataTables upon button click with an Ajax request

I have a piece of HTML code that represents a partial view: <table id="table_id" class="table table-inverse"> <thead class="thead-inverse"> <tr> <th>Select</th> ...

Adding data to each span and div using JavaScript is a simple task that can be achieved easily

What is the best way to add information to each span and div element using JavaScript? $(document).on("click",".selection-state",function(){ stateid = $(this).attr("rel"); $("#my_tooltip").html(data); } e ...

PyQt5: Extracting the signal from a QTableWidget using QComboBox

This may seem like a simple question for beginners, but I have tried searching for the answer without success. Within the application, there is a QTableWidget that includes a QComboBox, a QDoubleSpinBox, and some other standard items. I want to trigger t ...

The HTML page is failing to call the function in the JavaScript application

I recently started taking a YouTube Javascript course on chapter 34 titled "Make start button work" Javascript tutorial My HTML, CSS, and Javascript files are all located in the same folder. I am using VS Code along with the Live Server extension for codi ...

Using VB.NET to run JavaScript through Selenium's ChromeDriver

I've tried various methods in C# but I can't seem to get them working in VB.NET. It's possible that I'm not initializing it correctly. My goal is to run javascript on a loaded URL using the chromedriver. This is what my code looks like ...

Ways to identify if one object is positioned above another

So, here's the scenario: I'm trying to figure out how to detect when one element is positioned on top of another. Specifically, I'm dealing with SVG elements: <circle r="210.56" fill="#1ABCDB" id="01" priority="4" cx="658" cy="386">& ...

Go back to the top by clicking on the image

Can you help me with a quick query? Is it feasible to automatically scroll back to the top after clicking on an image that serves as a reference to jQuery content? For instance, if I select an image in the "Portfolio" section of , I would like to be tak ...

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

Troubleshooting the Timepicker import issue in ant design version 5.0.3

After updating ant design to version 5.0.3, I encountered the Uncaught Error: Cannot find module 'antd/lib/time-picker/style' at webpackMissingModule issue. Any suggestions on how to resolve this? I am seeking a solution for the error coming fro ...

Difficulty with changing JSON keys in jq not functioning as expected

My jq key assignment isn't working correctly. I attempted to follow the advice provided in this post for my specific scenario. Using jq how can I replace the name of a key with something else In my case, I am trying to change id to item_id. jq &apos ...

What is the best way to utilize AngularJS to make an HTTP PUT request while including an ID?

I've successfully developed a Restful API in Python that interacts with my database and a table named groups. Currently, I have scripts for GET & POST operations, and now I'm working on creating a script for PUT to update a group. In the HTML doc ...

Label Overlapping Issue in React Select

Utilizing react-select version ^5.1.0, I am encountering an issue where the word "select" overlaps with the options when scrolling. An image has been attached for better clarification. How can I eliminate the occurrence of the select word overlapping my op ...

Managing memory and CPU resources in NodeJS while utilizing MongoJS Stream

Currently, I am in the process of parsing a rather large dataset retrieved from MongoDB, consisting of approximately 40,000 documents, each containing a substantial amount of data. The dataset is accessed through the following code snippet: var cursor ...

Error: Module analysis.clustering.algorithms not found

I'm currently delving into Python code related to text summarization (https://github.com/giorgosera/pythia/blob/dev/analysis/summarization/summarization.py) but I encounter an error when trying to execute it: ImportError: No module named analysis.clu ...

The issue with history.push() functionality not functioning as expected within Firebase's authentication system when used in conjunction

I'm currently working on setting up authentication using React, Firebase Auth, and Context API. signin.js import React, { useEffect, useState } from 'react'; import { Form, Button, Container, Card } from 'react-bootstrap'; import ...

What are some potential causes of webpack-dev-server's hot reload feature not working properly?

Having an issue with my React project. When I try to use hot reload by running "npm start" or "yarn start" with webpack-dev-server configured (--hot flag), I'm getting the error message: [error message here]. Can anyone assist me in troubleshooting th ...

Running `grunt serve` with CORS enabled allows for cross

Our team utilizes grunt serve for live recompiling and reloading of our web application, allowing us to make edits and see changes in almost real-time. The webapp is built using AngularJS, which means that all interactions on the site are done through API ...

Show the item in the menu with a label that has either subscript or superscript styling

Within the realm of electrons, the application menu is specified: const menuTemplate = [ { label:"Menu Item 1", click(){ //define some behavior } } ]; Is there a method to exhibit the name of the menu item as Me ...

Press a designated button and select a checkbox within Selenium

I am having trouble clicking the "detail_search_button" and selecting the "판매중인 차량" checkbox. The issue arises when trying to locate the "detail_search_button". I attempted to use the "find" function in BeautifulSoup as shown below: from sele ...