printing from nested dictionaries in classes - python

Having isues figuring out why this particular setup isnt working.
class market(object):
def __init__(self, market, coin):
self.coin = coin
self.market = market
req = requests.get(f"http://bittrex.com/api/v1.1/public/getticker?market={market}-{coin}")
sum = requests.get(f"https://bittrex.com/api/v1.1/public/getmarketsummary?market={market}-{coin}")
self.address = req.json()
self.marketsum = sum.json()
def ticker(self):
while True:
print(self.address["result"])
time.sleep(5)
def marketsummary(self):
print(f"Market Summary for {coin}")
print('_' * 20)
print("Market Name: ", self.marketsum['result']['MarketName'])
print("High: ", self.marketsum['result']['High']))
print("Low: ", self.marketsum['result']['Low'])
print("Volume: ", self.marketsum['result']['Volume'])
print("Last: ", self.marketsum['result']['Last'])
print("BaseVolume: ", self.marketsum['result']['BaseVolume'])
print("TimeStamp: ", self.marketsum['result']['TimeStamp'])
print("Bid: ", self.marketsum['result']['Bid'])
print("Ask: ", self.marketsum['result']['Ask'])
print("OpenBuyOrders: ", self.marketsum['result']['OpenBuyOrders'])
print("OpenSellOrders: ", self.marketsum['result']['OpenSellOrders'])
print("Previous Day: ", self.marketsum['result']['PrevDay'])
print("Created: ", self.marketsum['result']['Created'])
print("DisplayMarketName: ", self.marketsum['result']['DisplayMarketName'])`
Ive previously used this method with static(?jaron?) variables in if statements, such as
usdt_ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=USDT-ADA")
btc_ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=BTC-ADA")
eth_ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=ETH-ADA")
print("Which trade pairing would you like for this coin?")
tradepair = input("> ")
if str.lower(tradepair) == "usdt" or "tether":
actual_ticker = usdt_ticker.json()
elif str.lower(tradepair) == "btc" or "bitcoin":
actual_ticker = btc_ticker.json()
elif str.lower(tradepair) == "eth" or "ethereum":
actual_ticker = eth_ticker.json()
else:
print("Sorry that trading pair isnt currently being monitored by this system")
print("Now viewing Cardano /", str.upper(tradepair), " trading." )
current_price = actual_ticker["result"]["Last"]
but with the self.marketsum['result']['MarketName'] its not working. If theres any input as to why this is happening and how to fix it I would be greatly appreciative. The error I am getting is
TypeError: list indicies must be integers or slices, not str

From the developer's guide, the json structure of a response from /public/getmarketsummary looks like:
{
"success" : true,
"message" : "",
"result" : [{
"MarketName" : "BTC-LTC",
"High" : 0.01350000,
"Low" : 0.01200000,
"Volume" : 3833.97619253,
"Last" : 0.01349998,
"BaseVolume" : 47.03987026,
"TimeStamp" : "2014-07-09T07:22:16.72",
"Bid" : 0.01271001,
"Ask" : 0.01291100,
"OpenBuyOrders" : 45,
"OpenSellOrders" : 45,
"PrevDay" : 0.01229501,
"Created" : "2014-02-13T00:00:00",
"DisplayMarketName" : null
}
]
}
Notice the result is actually a list containing a single element. They don't state why it is in a list and I can't get it to return a list with more than one element.
For now, it should be fine to change the lines accessing marketsum from
self.marketsum['result']['last']
to
self.marketsum['result'][0]['last']
Probably also add a check that the list is not empty.

Related

wrong key selection from dictionary

So I wrote a program that converted alphabets from a sentence to numbers. To understand whether the number was in the same word or another I made a distinction with "-" and "-". If a word is in the same line the numbers are separated by a "-" and if they are in another word they are separated by a "-". Like hi hi => 8-5-*-8-5-.
Now I was writing a program to do the opposite i.e convert numbers to alphabets using a dictionary. I wrote the dictionary like this -
Dictionary = {"26" : "z","25" : "y","24" : "x","23" : "w","22" : "v","21" : "u","20" : "t","19" : "s","18" : "r","17" : "q","16" : "p","15" : "o","14" : "n","13" : "m","12" : "l","11" : "k","10" :"j","1" : "a","2" : "b","3" : "c","4" : "d","5" : "e","6" : "f","7" : "g","8" : "h","9" : "i","*" : " "}
user_input = input("Please Enter a message: ")
count = user_input.count("-")
individual_number = user_input.split("-")
for i in range(0 , count):
for number in individual_number[i]:
individual_number[i] = individual_number[i].replace(number, Dictionary[number])
print(individual_number[i])
Now it Works for numbers from 1 - 9 but for 10 - 26, it does not work. For Example -
8-9-*-2-6- => h
i
b
f
But the same is for this one as well -
8-9-*-26- => h
i
bf (This should have been "Z")
I don't understand why it does that. it should take the whole number instead of taking each number one by one. Please help.
Also, I want it to print the whole sentence in one line/string. But I can't get it to do it. Please help with that too.
Thank you
To convert numbers to words use this one.
Dictionary = {"26" : "z","25" : "y","24" : "x","23" : "w","22" : "v","21" : "u","20" : "t","19" : "s","18" : "r","17" : "q","16" : "p","15" : "o","14" : "n","13" : "m","12" : "l","11" : "k","10" :"j","1" : "a","2" : "b","3" : "c","4" : "d","5" : "e","6" : "f","7" : "g","8" : "h","9" : "i","*" : " "}
user_input = input("Please Enter a message: ")
user_input = user_input.split('-')
output = ''
for a in user_input:
try:
output+=Dictionary[a]
except KeyError:
output+=''
print(output)
And for words to numbers use this one.
Dictionary = {"26" : "z","25" : "y","24" : "x","23" : "w","22" : "v","21" : "u","20" : "t","19" : "s","18" : "r","17" : "q","16" : "p","15" : "o","14" : "n","13" : "m","12" : "l","11" : "k","10" :"j","1" : "a","2" : "b","3" : "c","4" : "d","5" : "e","6" : "f","7" : "g","8" : "h","9" : "i","*" : " "}
Dictionary_ = {value:key for key,value in Dictionary.items()}
user_input = input("Please Enter a message: ")
output = ''
for a in user_input:
try:
output+=Dictionary_[a]
output+='-'
except KeyError:
output+=''
output = output[:-1]
print(output)
I think you're over-complicating things. Why the nested loop?
This seems to do what you want:
Dictionary = {"26" : "z","25" : "y","24" : "x","23" : "w","22" : "v","21" : "u","20" : "t","19" : "s","18" : "r","17" : "q","16" : "p","15" : "o","14" : "n","13" : "m","12" : "l","11" : "k","10" :"j","1" : "a","2" : "b","3" : "c","4" : "d","5" : "e","6" : "f","7" : "g","8" : "h","9" : "i","*" : " "}
user_input = input("Please Enter a message: ")
individual_number = user_input.split("-")
for number in individual_number:
print(Dictionary[number],end='')

iteration over 2d list in python and printing headings for each element

I am trying to work out how to iterate over a list and print out each item with a print statement describing what element is. my project is to create a user management system and print out something similar to the image I have attached.
The output I am trying to produce
The output I am getting
My code:
records = 0
userFirst = ["John"]
userLast = ["Doe"]
autoUsername = ["Johndoe91"]
autoPassword = ["123456789"]
hiddenPassword = ["*****789"]
userRole = ["User"]
userDept = ["Administration"]
users = []
confidentialUserDetails = []
users.append(userFirst + userLast + userRole + userDept + autoUsername + autoPassword)
confidentialUserDetails.append(users)
for row in range(len(confidentialUserDetails)):
records += 1
print("-" * 25)
print("Record: ", records)
for col in range(len(confidentialUserDetails[row])):
print(confidentialUserDetails[row][col])
Any help would be greatly appreciated. :)
Your data structures are unusual. I'm assuming that those lists are going to be provided to your code somehow and will, in practice, have multiple user details appended to them so that they are all the same length.
Anyhow, you can achieve the output you're looking for with some readable f-strings like this:
from functools import reduce
userFirst = ["John"]
userLast = ["Doe"]
autoUsername = ["Johndoe91"]
autoPassword = ["123456789"]
hiddenPassword = ["*****789"]
userRole = ["User"]
userDept = ["Administration"]
for row in range(len(userFirst)):
s = (f"""\
Name : {userFirst[row]} {userLast[row]}
Role : {userRole[row]}
Department : {userDept[row]}
Username : {autoUsername[row]}
Password : {hiddenPassword[row]}""")
maxlen = reduce(lambda x,y: max(x, len(y)), s.split("\n"), 0)
print(f"{s}\n{'-'*maxlen}\n")
Output:
Name : John Doe
Role : User
Department : Administration
Username : Johndoe91
Password : *****789
------------------------------
I created a dictionary called user instead of your list and after that I appended it to the second list and finally I printed the key and the value of the dictionary.
Also to get the full name I joined userFirst and userLast as string.
Code:
records = 0
userFirst = ["John"]
userLast = ["Doe"]
autoUsername = ["Johndoe91"]
autoPassword = ["123456789"]
hiddenPassword = ["*****789"]
userRole = ["User"]
userDept = ["Administration"]
confidentialUserDetails = [] # 2d list for asterisked passwords
users={'Name' : [' '.join(userFirst + userLast)] ,'Role' : userRole , 'Departement' : userDept ,'Username' : autoUsername ,'Password' : hiddenPassword }
confidentialUserDetails.append(users)
for user in confidentialUserDetails:
records += 1
print("-" * 25)
print("Record: ", records)
for ele,v in user.items():
print(ele,':',v[0])
Output:
-------------------------
Record: 1
Name : John Doe
Role : User
Departement : Administration
Username : Johndoe91
Password : *****789
Using a dictionary or f strings like the two other answers suggested is probably the best. But if you just want to use your current code to print your desired output, you can simply grab each item by its index number in your print statement.
Change the line:
print(confidentialUserDetails[row][col])
To something like this:
print("Name : ", confidentialUserDetails[row][col][0], confidentialUserDetails[row][col][1])
print("Role: : ", confidentialUserDetails[row][col][2])
Output:
-------------------------
Record: 1
Name : John Doe
Role: : User

create dict keys depending on the number of times the same value occurs

I have a dict as below, if the same value is found more tahn once then the dict key must be created with incremental numbering.
TT = {
"TYPE_1" : ['ERROR'],
"TYPE_2": ['FATAL'],
"TYPE_3" : ["TIME_OUT"],
"TYPE_4" : ['SYNTAX'],
"TYPE_5" : ['COMPILE'],
}
m1 = "ERROR the input is not proper"
m2 = "This should have not occured FATAL"
m3 = "Sorry TIME_OUT"
m4 = "SYNTAX not proper"
m5 = "u r late its TIME_OUT"
The value "TIME_OUT" occur twice in the search.
count = 0
for key in TT.keys():
print(key)
Key_1 = key
while key_1 in TT:
count = count+1
key_1 = key + "_{}".format(count)
The above code gives error Key_1 not defined.
Expected OUTPUT:
if the same value is occuring more than once then the dict key should be created with incremental numbering "TYPE_3_1" : ["TIME_OUT"],
TT = {
"TYPE_1" : ['ERROR'],
"TYPE_2": ['FATAL'],
"TYPE_3" : ["TIME_OUT"],
"TYPE_3_1" : ["TIME_OUT"],
"TYPE_4" : ['SYNTAX'],
"TYPE_5" : ['COMPILE'],
}
Please suggest on this.
There can be a much efficient way of solving this if you can rethink about some of the data structure but if that is not an option you may be able to try this.
inputs = ["ERROR the input is not proper",
"This should have not occured FATAL",
"Sorry TIME_OUT",
"SYNTAX not proper",
"u r late its TIME_OUT"]
basic_types = {
"TYPE_1" : ['ERROR'],
"TYPE_2": ['FATAL'],
"TYPE_3" : ["TIME_OUT"],
"TYPE_4" : ['SYNTAX'],
"TYPE_5" : ['COMPILE'],
}
type_counts = {}
results = {}
for sentence in inputs:
for basic_type in basic_types:
if basic_types.get(basic_type)[0] in sentence:
type_counts[basic_type] = type_counts.get(basic_type, 0) + 1
if type_counts[basic_type] == 1:
results[basic_type] = [basic_types.get(basic_type)[0]]
else:
results[basic_type+"_{}".format(type_counts[basic_type] - 1)] = [basic_types.get(basic_type)[0]]
print(results)

I have a python TypeError and I don't know how to fix it

So I have the following code:
import random
pizza_toppings = ["bacon", "cheese", "chicken", "pepperoni", "olives"]
pizza_sauce = ["alfredo", "marinara", "ranch", "BBQ"]
def pizza(number_of_toppings):
final_sauce = random.choice(pizza_sauce)
final_toppings = []
for i in range(number_of_toppings):
final_topping = random.choice(pizza_toppings)
final_topping(final_toppings)
final_result = print("Your pizza with ", final_topping, " with ", final_sauce, " is ready I guess...")
return final_result
pizza(2)
It's giving me the error "TypeError: 'str' object not callable." How do I fix this?
I assume this line
final_topping(final_toppings)
should be
final_toppings.append(final_topping)
Also the return of print is None, so final_result will be None.
I replaced final_toppings by final_toppings_list so it makes it clearer :
import random
pizza_toppings = ["bacon", "cheese", "chicken", "pepperoni", "olives"]
pizza_sauce = ["alfredo", "marinara", "ranch", "BBQ"]
def pizza(number_of_toppings):
final_sauce = random.choice(pizza_sauce)
final_toppings_list = []
for i in range(number_of_toppings):
final_topping = random.choice(pizza_toppings)
final_toppings_list.append(final_topping)
final_result = "Your pizza with ", final_toppings_list, " with ", final_sauce, " is ready I guess..."
return final_result
print(pizza(2))
It´s because you´re using the string final_topping as a function. Just delete that line and you´re good.
You don't necessarily need to append final_topping to a final_toppings list if you want to use only one element of your pizza_toppings list (later in final_result).
I commented the two lines in your script and used python f-strings to format final_result in a convenient way..
import random
pizza_toppings = ["bacon", "cheese", "chicken", "pepperoni", "olives"]
pizza_sauce = ["alfredo", "marinara", "ranch", "BBQ"]
def pizza(number_of_toppings):
final_sauce = random.choice(pizza_sauce)
#final_toppings = []
for i in range(number_of_toppings):
final_topping = random.choice(pizza_toppings)
#final_toppings.append(final_topping)
final_result = (
f"Your pizza with {final_topping} "
f"and {final_sauce} is ready I guess..."
)
return final_result
print(pizza(2))

Ranges as values in dictionary and using these in if else statement

I am new to python basically, I want this dictionary:
ages = {
"toddler" : range(0,2),
"kid" : range(3,12),
"teen" : range(13,19),
"young adult" : range(20,25),
"adult" : range(26,39),
"middle-aged" : range(40,60),
"old" : range(61,99)
}
I have a target_age variable which holds the random value in any of the keys in the above mentioned dictionary:
target_age = random.choice(list(ages))
my api is going to return an "age" which I want to compare if its in the range of the randomized "target_age" variable
How should I code my "if and else statement" if I want for example the returned_age is 25 and the target_age is "young adult" then it should satisfy the condition otherwise it should return false
returned_age in ages[target_age], as mentioned by #khelwood above, sounds like it would accomplish what you want:
ages = {
'toddler': range(0,3),
'kid': range(3,13),
'teen': range(13,20),
'young adult': range(20,26),
'adult': range(26,40),
'middle-aged': range(40,61),
'old': range(61,99)
}
# generate a random target_age
target_age = np.random.choice(list(ages))
# suppose the returned_age from the API is 25
returned_age = 25
print('target_age = ' + str(target_age))
print('returned_age = ' + str(returned_age))
print('returned_age in target_age? ' + str(returned_age in ages[target_age]))
Here is the output from one particular run:
target_age = old
returned_age = 25
returned_age in target_age? False

Categories

Resources