2D list python unable to get it right - python

im trying to the below code but when I run the function for examnple:
finder("001-987654-003")
Nothing is happening. What went wrong?
def finder(lookupvalue):
user_list = [
["Account number","Currency","Balance"],
["001-987654-003","USD",1300.72],
["001-919202-100","EUR",105.01],
["001-905700-100","EUR",305.00],
["001-908415-307","CHF",20804.98],
["011-974777-200","PLN",208.15],
["001-931654-001","USD",450.7]
]
for row in user_list:
if user_list[0][0]==lookupvalue:
print("yes")

You have to use row instead of user_list:
def finder(lookupvalue, lookuplist, col_index):
for row in lookuplist:
if row[0] == lookupvalue:
print(row[col_index - 1])
finder("001-919202-100", user_list, 2)
That's because if you use user_list[0][0] in the for loop it'll constantly refer to "Account number" whilst row[0] will go through the different lists, looking up the account number.
But as one of the comments said, a dictionary would probably be better for this task.

try this:
user_list = [
["Account number", "Currency", "Balance"],
["001-987654-003", "USD", 1300.72],
["001-919202-100", "EUR", 105.01],
["001-905700-100", "EUR", 305.00],
["001-908415-307", "CHF", 20804.98],
["011-974777-200", "PLN", 208.15],
["001-931654-001", "USD", 450.7]
]
def finder(lookupvalue, lookuplist, col_index):
for row in user_list:
if row[0] == lookupvalue:
print(row[col_index-1])
finder("001-919202-100", user_list, 2)
output:
EUR

Try using a dictionary:
user_list = {
"Account Number": ["001-987654-003", "001-919202-100", "001-905700-100"],
"Currency": ["USD", "EUR", "EUR"],
"Balance": [1300.72, 105.01, 305.00]
}
Seems more appropriate in your case as you're trying to store different lists (I think).

Related

How get variable (which does not exist in a message) from JSON message?

I have a JSON message. And I want to return values that stand for "Brand", but in this message it does not exist, so this value needs to be replaced by another. How can I do that? I tried with try/except, however the values are not replaced.
import json
message = [
{
"ID": 48,
"Type": "Update",
"UpdateType": "Quote",
"Key": {
"Service": "Online",
"Name": "Audi"
},
"Fields": {
"Buyers": 1000,
"Sellers": 500,
"Year": 2020
}
}
]
data=json.loads(message)
#data[0]['ID'] this works as there is ID
try:
data[0]['Brand']
except :
9999 #no output seen
From your question:
I want to return values that stand for "Brand", but in this message, the "Brand does not exist, so this value is needed to be replaced by another. How can I do it?
So you want to retrieve entry from a list, then get item from the entry for example Brand.
and if there is no such Brand in the entry then add Brand item to the entry.
Am I right?
if so, your code may changed to:
import json
message = '[{"ID":48,"Type":"Update","UpdateType":"Quote","Key": {"Service":"Online","Name":"Audi"},"Fields":{"Buyers":1000,"Sellers":500,"Year":2020}}]'
data=json.loads(message) # here message should be a json-string
#data[0]['ID'] this works as there is ID
try:
data[0]['Brand']
except KeyError:
# 9999 #no output seen
data[0]['Brand'] = NewItem # the item you want to replace
You need to itinerante thru the list and check in one of then contains the key. This being done on a python objects and not on a raw json string
message = [{"ID":48,"Type":"Update","UpdateType":"Quote","Key":{"Service":"Online","Name":"Audi"},"Fields":{"Buyers":1000,"Sellers":500,"Year":2020}}]
def item_exists_ofd(dic_list, item):
for dic in dic_list:
if item in dic:
return dic
return None
if __name__ == '__main__':
match = item_exists_ofd(message, 'Brand')
if match:
print(match['Brand'])
else:
print('Brand, not found')
match = item_exists_ofd(message, 'ID')
if match:
print(match['ID'])
else:
print('ID, not found')

How to show more variables in modules

Im just starting to learn practice it however my problem I bet is easy to resolve I’m trying my best but my knowledge is too low to solve this out , I’ve try commas brackets but still didn’t work I just want to get print the name country and age , sorry for newbie question please help 👍🏼💪🤠
Main.py
import one
a = one.person1["name"]
b = one.person2["name"]
c = one.person3["name"]
def input():
print(one(name))
One.py
person1 = {
"name": "John",
"age": "6",
"country": "Norway"
}
person2 = {
"name": "Jn",
"age": "36",
"country": "Norway"
}
person3 = {
"name": "krun",
"age": "36",
"country": "Norway"
}
If you want to display one person then use every key separatelly
print( one.person1["name"], one.person1["age"], one.person1["country"] )
And then you can format output
print('name =', one.person1["name"])
print('age =', one.person1["age"])
print('country =', one.person1["country"])
You can also display directly print(one.person1) but then you can't format output.
If you want to display all persons then keep them on list and then you can use for-loop
persons = [one.person1, one.person2, one.person2]
for item in persons:
print( item["name"], item["age"], item["country"] )
If you don't know keys then you can use .keys() or .items() in dictionary
for item in persons:
for key, value in item.items():
print(key, '=', value)
if you want to get key from user then
key = input("what to show: ")
print(one.person1[key])
print(one.person2[key])
print(one.person3[key])
or better keep persons on list and use for-loop
key = input("what to show: ")
persons = [one.person1, one.person2, one.person2]
for item in persons:
print( item[key] )

Python Dict Key Error. How do I loop through nested dict and check for a key

I have the following nested dict below which I'm trying to loop through. Well, not necessarily loop through but I just want to check that the label has a value "EDD". If it does then I want to trigger some other action.
My problem is that I keep getting an error for labels key error.
Please how do I do this.
message.data = {
"messages": [{
"to": "wa-id",
"from": "another-wa-id",
"type": "text",
"_vnd": {
"v1": {
"direction": "outbound",
"in_reply_to": "an-earlier-inbound-external-id",
"author": {
"name": "the name of the author",
"type": "SYSTEM | OPERATOR",
},
"labels": [{
"uuid": "the-uuid",
"value": "EDD"
}]
}
}
}, ]
}
My code looks like so:
whatsapp_contact_id = message.data
print(whatsapp_contact_id.keys())
list_data = whatsapp_contact_id["messages"]
print(list_data)
for dictionary_data in list_data:
print(dictionary_data)
dictionary_keys = dictionary_data.items()
print(dictionary_keys)
"""
EDD_label = dictionary_data["labels"]
"""
EDD_label = dictionary_data.get('labels', 'could not find')
print("The label is below")
print(EDD_label)
Assuming the structure stays constant, what you want is:
whatsapp_contact_id = message.data
list_data = whatsapp_contact_id.get("messages")
for dictionary_data in list_data:
dictionary_data_2 = dictionary_data.get("_vnd").get("v1")
labels_data = dictionary_data_2.get("labels")
print(labels_data)
for EDD in labels_data:
EDD_string = EDD.get("value", "EDD label not present")
print(EDD_string)
Also, you appear to have triple-pasted your code.
Edited to include final code from OP
Thanks everyone especially #tennoshi.
This works:
whatsapp_contact_id = message.data
list_data = whatsapp_contact_id.get("messages")
for dictionary_data in list_data:
dictionary_data_2 = dictionary_data.get("_vnd").get("v1")
labels_data = dictionary_data_2.get("labels")
print(labels_data)
for EDD in labels_data:
EDD_string = EDD.get("value", "EDD label not present")
print(EDD_string)```

How to remove empty { } from JSON file using python

I have done my research but I couldn't find any answers that worked.
I have the following JSON file:
{
"Cars": [{
"Manufacturer": "Audi",
"model": "R8",
"price": 50000,
"a": {
"n": "1",
"street": "ABC Street",
"city": "London",
"postcode": "TW1 1AA"
}
},
{
"Manufacturer": "Ford",
"model": "Fiesta",
"price": 10000,
"a": {
"n": 2,
"street": "DEF street",
"town": "London",
"PostCode": "TW2 2AB"
}
},
{
"Manufacturer": "VW",
"model": "Polo",
"price": 5000,
"a": {
"n": "3",
"Street": "GHI Street",
"town": "London",
"postcode": "TW3 3CD"
}
}
]
}
In my python file, to remove the JSON elements, I am using the following:
deletecar = int(input("Enter price of car to delete: "))
for item in data["Cars"]:
if deletecar == item["price"]:
item.pop("Manufacturer")
item.pop("model")
item.pop("price")
item.pop("a")
with open("testjson.json", 'w') as f:
json.dump(data, f)
When I run this, if I delete the first car in the JSON file, I find this:
{"Cars": [{}, {"Manufacturer": "Ford", ...
If I now run my program again, but I try to search for cars, the program won't work due to these empty braces.
So how can I remove them using Python?
Thanks in advance.
You need to remove the item itself, which means you need two steps:
find the index at which the item you want to remove is
remove the item from the list (with del)
And you don't need to "empty" the dict as that's not what you're looking for.
Alternatively, you could create a brand new list without the offending item using a list comprehension or a filter call e.g.
deletecar = int(input("Enter price of car to delete: "))
data['Cars'] = [
item for item in data['Cars']
if item['price'] != deletecar
]
with open("testjson.json", 'w') as f:
json.dump(data, f)
(note: this "removes" all items which match, rather than just the first as your code does).
Also you probably want to save after you're done processing, not during processing.
Since it's a list, you can find the index values in your list that match your price input. Then remove those elements from values in the 'Cars' list
deletecar = int(input("Enter price of car to delete: "))
# Get the index values of where the item is located
index_to_delete = []
for item in data["Cars"]:
if deletecar == item["price"]:
index_to_delete.append(data["Cars"].index(item))
# Since the index values will change as you delete them,
# you will have to remove them in reverse order (in case there's more than 1
# item being removed
for i in reversed(index_to_delete):
del data["Cars"][i]
# write to file
with open("testjson.json", 'w') as f:
json.dump(data, f)

how to get specific value in python dictionary?

I call an api via python and return this code as response:
{
"cast": [
{
"character": "Power",
"name": "George"
},
{
"character": "Max",
"job": "Sound",
"name": "Jash"
},
{
"character": "Miranda North",
"job": "Writer",
"name": "Rebecca"
}
]
}
I am trying to get the value of Rebecca because i need to get the Writer.
So i wrote:
for person in cast # cast is the variable keeps whole code above NOT inside the dict:
if person["job"] == "Writer":
writer = person["name"]
but it gives me:
KeyError at search/15
u'job'
how can i get the value?
FULL CODE:
writer = ""
for person in api['cast']:
if person.get('job') == 'Writer':
writer = person.get('name')
return render(request, 'home.html', {
'writer': writer
})
home.html:
<p>{{writer}}</p>
That's because not all elements in the list have the job key.
Change to:
for person in cast #whole code above:
if person.get('job') == 'Writer':
writer = person.get('name')
One liner to find one writer.
writer = next((person for person in api['cast'] if person.get('job') == 'Writer'), None)
One liner to find all writers.
writers = [person for person in api['cast'] if person.get('job') == 'Writer']
Syntax for dictionary get() method:
dict.get(key, default=None)
Parameters
key: This is the Key to be searched in the dictionary.
default: This is the Value to be returned in case key does not exist.
You need to specify the default value for get in case the key doesn't exist.
>>> for person in api['cast']:
... if person.get('job', '') == 'Writer':
... writer = person.get('name')
person.get(u"job") == "Writer"
for person in cast["cast"]:
# cast is the variable keeps whole code above NOT inside the dict
if person["job"] == "Writer":
writer = person["name"]
try this
cast["cast"] == Value of Key "cast" , which in turn is list of Dicts
and for looping through each Dictionary as person

Categories