'How to access values in dictionary

import json

x = {
  "name": "John",
  "age": 30,
  "married": True,
  "divorced": False,
  "children": ("Ann","Billy"),
  "pets": None,
  "cars": [
    {"model1": "BMW 230", "mpg": 27.5},
    {"model2": "Ford Edge", "mpg": 24.1}
  ]
}

# use . and a space to separate objects, and a space, a = and a space to separate keys from their values:
#print(json.dumps(x, indent=4, separators=(". ", " = ")))

z = json.dumps(x["model1"], indent=4, separators=(". ", " = "))

print(z)

** I am trying to access the key and the associated values from the car models. Can anybody show me how to access the models separately**



Solution 1:[1]

Your models are inside the array corresponding to the key of "cars". You can retrieve them like this:

[car['model1'] for car in x['cars'] if 'model1' in car.keys()]

But this only retrieves for the key of "model1" in each car dictionary.

If you want all the models, it gets a little more complicated where you have to include to number:

[car[f'model{i}'] for i, car in enumerate(x['cars'], 1)]

If your intention is to retrieve the models for each car, you need to have the keys to be the same to make your life easier:

import json

x = {
  "name": "John",
  "age": 30,
  "married": True,
  "divorced": False,
  "children": ("Ann","Billy"),
  "pets": None,
  "cars": [
    {"model": "BMW 230", "mpg": 27.5},  # Changed "model1" to "model"
    {"model": "Ford Edge", "mpg": 24.1} # Changed "model2" to "model"
  ]
}

With this, you can then simply do:

[car['model'] for car in x['cars']]

Solution 2:[2]

I am new here but the solution to your problem might be to use the .get() method followed by the list indexing for the list element you want to choose and again using the dictionary way to get the value if you know the key.

My suggestion is to use this x.get("cars")[0]["model1"] in place of x["model1"] This works for python3

Solution 3:[3]

I think this is you want import json

x = {
    "name": "John",
    "age": 30,
    "married": True,
    "divorced": False,
    "children": ("Ann", "Billy"),
    "pets": None,
    "cars": [
        {"model1": "BMW 230", "mpg": 27.5},
        {"model2": "Ford Edge", "mpg": 24.1}
    ]
}

# # use . and a space to separate objects, and a space, a = and a space to separate keys from their values:
# #print(json.dumps(x, indent=4, separators=(". ", " = ")))
newArrayModels = []
for model in x['cars']:
    newModel = ''
    for key in model:
        if key != 'mpg':
            newModel += '{"' + model[key] + '":"'
        else:
            newModel += str(model[key]) + '"}'
    # print(newModel)
    newArrayModels.append(json.loads(newModel))
x['cars'] = newArrayModels
print(json.dumps(x, indent=4, separators=(". ", " = ")))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rcshon
Solution 2 Hkukka
Solution 3 n-ata