Add a value to a pre-existing key in a dictionary? [duplicate] - python

This question already has answers here:
How can I add new keys to a dictionary?
(19 answers)
Closed 4 years ago.
I'm trying to add a third value to existing dictionary keys in Python. I'm sure this is probably easy, but I'm fairly new to coding so each way I've tried has thrown an error. Below is an example of what I tried which resulted in a syntax error. I also tried making the colon an equal sign but I got the message can't assign to a literal which I figure is due to the presence of two different = in the same line of code.
student = [
{ "name": "Kellie", "student_id": 12345},
{ "name": "James", "student_id": 39875},
{ "name": "Katie", "student_id": 24680},
]
student[0] = "lastName" : "Vee"
student[1] = "lastName" : "Tee"
student[2] = "lastName" : "Zee"

Try to add element like this:
student[0]["grade"] = "1"
It will add here: { "name": "Kellie", "student_id": 12345} new key "grade" and asign the value of 1.

Related

Navigating JSON with variable keys in Python? [duplicate]

This question already has answers here:
Use Variable As Dictionary Key Set
(2 answers)
How to use a dot "." to access members of dictionary?
(36 answers)
Closed last month.
Lets say I have some json like so store in a variable called data
{
"print": {
"ams": { "exists": 1},
"fan_speed": 29,
"reports": [
{"name": "foo"},
{"name": "bar"}
]
}
}
Now I've got a variable which is the key i want to return stored in a variable called key for example print.fan_speed, print.ams.exists, print.reports[0].name
What I want to is something like data.get(key). What is the best way to approach this?
The following should work its way into your data, including indexing into lists:
import re
data = {
"print": {
"ams": { "exists": 1},
"fan_speed": 29,
"reports": [
{"name": "foo"},
{"name": "bar"}
]
}
}
def value_of(data, location):
for part in location.split("."):
match = re.match(r"(.*)\[(\d+)\]$", part)
if match:
name, index = match.groups()
data = data.get(name)[int(index)]
else:
data = data.get(part)
if not data:
return None
return data
print(value_of(data, "print.ams.exists"))
print(value_of(data, "print.reports[1].name"))
Result:
1
bar
It could do with a little rationalisation as it will return None for a non-existent key, but will error on a bad index - it should do one or the other depending on your requirements but the concept is there.
The concept is to take each '.' separated element of the string in turn, using it to dig further into the data structure. If the element matches the syntax of 'name[index]' using the regex, the component is treated as a list and the indexth element is extracted.

Python search and replace whilst caching [duplicate]

This question already has answers here:
How can I make a dictionary (dict) from separate lists of keys and values?
(21 answers)
Closed 4 months ago.
I'm attempting to search and replace using information from 2 lists, this is whilst caching any replacements that have been done so the same corresponding values can be given.
For example, I have the following -
names = ["Mark","Steve","Mark","Chrome","192.168.0.1","Mark","Chrome","192.168.0.1","192.168.0.2"]
type = ["user","user","user","process","address","user","process","adress","address"]
And I'm hoping to get the following output -
{
"Mark":"user1",
"Steve":"user2",
"Chrome":"process1",
"192.168.0.1":"adress1",
"192.168.0.2":"adress2"
}
So trying to use the type in the the 2nd list to determine the item in the first list's corresponding value.
Hope this makes sense, is this possible? Any help would be appreciated.
I would recommend you use a dictionary personally.
names = {
"Mark": "user",
"Steve": "user2",
"Chrome": "process1",
"192.168.0.1": "address1",
"192.168.0.2": "address2"
}
print(names["Mark"])
By using this dictionary you can precisely tap into the name you'd like to information of or anything else you want. It is also a little more readable
To form a dictionary from said values you can iterate the range and access values with the same index:
output = {names[i]: types[i] for i in range(len(names))}
Also refrain from using variable name type because it's already taken by a builtin Python syntax.
Looks like you're also trying to store / retrieve the count of the types (i.e. "user1", "user2, "address1", etc.). Hence, we need another data structure to keep count of the types already registered in our "hashmap" (dictionary in python). In the below solution, we use the type_cache.
The code should work as is.
from collections import defaultdict
names = ["Mark", "Steve", "Mark", "Chrome", "192.168.0.1", "Mark", "Chrome", "192.168.0.1", "192.168.0.2"]
types = ["user", "user", "user", "process", "address", "user", "process", "address", "address"]
expected = {
"Mark": "user1",
"Steve": "user2",
"Chrome": "process1",
"192.168.0.1": "address1",
"192.168.0.2": "address2"
}
def process_names_and_types(names, types):
result = {}
type_cache = defaultdict(int)
for name, type_ in zip(names, types):
if name not in result:
type_cache[type_] += 1
result[name] = f"{type_}{type_cache[type_]}"
return result
if __name__ == "__main__":
actual = process_names_and_types(names, types)
assert actual == expected, f"Expected: {expected}, Actual: {actual}"

I need help making a program that will take random values of a dictionary and put them in another

This is meant for quiz I am trying to program in python. I have no ideas on how to proceed with this part of my program, since I'm fairly new to programming, but essentially I'm trying to set the key values of dico_q_ran to the values taken randomly from q_bank.
q_bank = {1 : {
"question" : "",
"answer" : ""
},
2 : {
"question" : "",
"answer" : ""
},
3 : {
"question" : "",
"answer" : ""}
etc...
25 : {
"question" : "",
"answer" : ""}
dico_q_ran = {0, 1 , 2, ...., 10}
for i in range(1, 11):
key_rand = (random.randrange(0,26))
dico_q_alea[i] = banque_de_questions[key_rand]
Sorry if the naming is a bit weird, I did light translation of the names from french so it would make a bit more sense for english speakers.
There are few problems here. Firstly, dico_q_ran is defined as a set, not a dict, so dico_q_alea[i] assignment is not possible. If you want it to be a dict, just init it empty as dico_q_ran = {}. I'd consider using lists instead, though.
Secondly, I'd suggest using lists for both q_bank and dico_q_ran, since your keys are sequential numbers, and that's what lists are for:
q_bank = [
{
"question": "...",
"answer": "...",
},
}
That will also help you fix another problem more easily. Current randomization doesn't guarantee that the same question won't be used twice. With lists it's getting as simple as:
dico_q_alea = random.sample(q_bank, 10)

Python: Find certain element in Array with given value [duplicate]

This question already has answers here:
Check if a given key already exists in a dictionary
(16 answers)
Closed 1 year ago.
Given my sample array:
json_data = data: [
{
'item_name' : "bag",
'item_price' : 12.99,
'item_stock' : 55
},
{
'item_name' : "jacket",
'item_price' : 8.99,
'item_stock' : 42
},
{
'security_check' : "maximum",
'item_name' : "jewelry",
'item_stock' : 10
},
{
'security_check' : "minimum",
'item_name' : "leather",
'item_stock' : 5
}
]
i want to find elements with the "security_check" element. some elements do not have that and im trying to get the item_name of elements with security_check
This is the function im currently calling:
def array_parse_for_item_name(json_data, name):
for entry in json_object:
if entry["security_check"] in json_object:
print(str(entry["item_name"]))
print(str(entry["item_stock"]))
but right now all im getting is: KeyError: 'security_check' and i assume it's because some elements do not have that key
Any help would be much appreciated. Thanks in advance.
Check if it is one of keys rather than try retrieve its' value, i.e. replace
if entry["security_check"] in json_object
using
if "security_check" in entry.keys()

Python returning key value pair from JSON object [duplicate]

This question already has answers here:
Python Accessing Nested JSON Data [duplicate]
(4 answers)
Closed 5 years ago.
I'm trying to return the 'publisher' and 'title' values of the first entry in this JSON object.
{
"count": 30,
"recipes": [{
"publisher": "Closet Cooking",
"f2f_url": "htt//food2forkcom/view/35171",
"title": "Buffalo Chicken Grilled Cheese Sandwich",
"source_url": "htt//wwwclosetcookingcom/2011/08/buffalo-chicken-grilled-cheese-sandwich.html",
"recipe_id": "35171",
"image_url": "htt//staticfood2forkcom/Buffalo2BChicken2BGrilled2BCheese2BSandwich2B5002B4983f2702fe4.jpg",
"social_rank": 100.0,
"publisher_url": "htt//closetcooking.com"
}, {
"publisher": "All Recipes",
"f2f_url": "htt//food2fork.com/view/29159",
"title": "Slow Cooker Chicken Tortilla Soup",
"source_url": "htt//allrecipescom/Recipe/Slow-Cooker-Chicken-Tortilla-Soup/Detail.aspx",
"recipe_id": "29159",
"image_url": "htt//staticfood2forkcom/19321150c4.jpg",
"social_rank": 100.0,
"publisher_url": "htt//allrecipescom"
}]
}
When I run this code, i can return the object minus the count part at the start.
r = requests.post(url, data = {"key":"aeee9034f8d624f0e6c57fe08e2fd406","q":"chicken"})
recipe=r.json()
print(recipe['recipes'])
However when I try to run:
print(recipe['recipes']['publisher'])
I get the error:
TypeError: list indices must be integers or slices, not str
What should I be doing in my code to print the information:
Closet Cooking, Bacon Wrapped Jalapeno Popper Stuffed Chicken
recipe['recipes'] is a list of objects, thus you can iterate over it:
To return the 'publisher' and 'title' values of the first entry in this JSON object you can use list comprehension and get the first element of the resulting collection:
recipes = [{element['publisher']: element['title']} for element in recipe['recipes']][0]
This gives you a bit of flexibility if you want to expand the result and include more fields, or more elements in the returned list.
The 'recipes' key contains a list of multiple recipes
recipe['recipes'][0]['publisher']
will return the publisher of the first recipe in the list.

Categories

Resources