Trouble calling Dictionary using Variable using Python - python

I have only been working with python for a few months,
so sorry if I am asking a stupid question. I am having
a problem calling a dictionary name using a variable.
The problem is, if I use a variable to call a dictionary & [] operators,
python interprets my code trying to return a single character in the string
instead of anything within the dictionary list.
To illustrate by an example ... let's say I
have a dictionary list like below.
USA={'Capital':'Washington',
'Currency':'USD'}
Japan={'Capital':'Tokyo',
'Currency':'JPY'}
China={'Capital':'Beijing',
'Currency':'RMB'}
country=input("Enter USA or JAPAN or China? ")
print(USA["Capital"]+USA["Currency"]) #No problem -> WashingtonUSD
print(Japan["Capital"]+Japan["Currency"]) #No problem -> TokyoJPY
print(China["Capital"]+China["Currency"]) #No problem -> BeijingRMB
print(country["Capital"]+country["Currency"]) #Error -> TypeError: string indices must be integers
In the example above, I understand the interpreter
is expecting an integer because it views the value
of "country" as a string instead of dictionary...
like if I put country[2] using Japan as input (for example),
it will return the character "p". But clearly that
is not what my intent is.
Is there a way I can work around this?

You should put your countries themselves into a dictionary, with the keys being the country names. Then you would be able to do COUNTRIES[country]["Capital"], etc.
Example:
COUNTRIES = dict(
USA={'Capital':'Washington',
'Currency':'USD'},
Japan={'Capital':'Tokyo',
'Currency':'JPY'},
...
)
country = input("Enter USA or Japan or China? ")
print(COUNTRIES[country]["Capital"])

Disclaimer: Any other way of doing it is definitely better than the way I'm about to show. This way will work, but it is not pythonic. I'm offering it for entertainment purposes, and to show that Python is cool.
USA={'Capital':'Washington',
'Currency':'USD'}
Japan={'Capital':'Tokyo',
'Currency':'JPY'}
China={'Capital':'Beijing',
'Currency':'RMB'}
country=input("Enter USA or Japan or China? ")
print(USA["Capital"]+USA["Currency"]) #No problem -> WashingtonUSD
print(Japan["Capital"]+Japan["Currency"]) #No problem -> TokyoJPY
print(China["Capital"]+China["Currency"]) #No problem -> BeijingRMB
# This works, but it is probably unwise to use it.
print(vars()[country]["Capital"] + vars()[country]['Currency'])
This works because the built-in function vars, when given no arguments, returns a dict of variables (and other stuff) in the current namespace. Each variable name, as a string, becomes a key in the dict.
But #tom's suggestion is actually a much better one.

Related

Passing a Decimal(str(value)) to a dictionary for raw value

I'm needing to pass values to a dictionary as class 'decimal.Decimal', and the following keeps happening:
from decimal import *
transaction_amount = 100.03
transaction_amount = Decimal(str(transaction_amount))
item = {
'transaction_amount': transaction_amount
}
print(item)
Results:
{'transaction_amount': Decimal('100.03')}
How do I attain the raw 100.03 result, rather than Decimal('100.03')?
This is what I want the dictionary to have saved:
{'transaction_amount': 100.03)}
When I do:
print(transaction_amount)
The result is as expected:
100.03
So where am I going wrong?
I don't see any reason why this question should be downvoted.
When you ask python to print an object, it'll print the textual representation of that object.
Here your variable item is a dictionnary, so its representation is as follow:
{ key: value [, repeat]}
If you want the value inside your dictionnary, you would have to go at the specified key like so :
print(item[transaction_amount])
So basically, your code was fine and your use of decimal too, but you weren't testing it the good way. ;) Happens a lot.
Edit:
It's worth noting that, since what you are getting within the dictionnary object is Decimal(100.03), even when printing the value of the key-value pair as I showed previously, you won't get a pure 100.03, but probably Decimal(100.03).
I'll search some documentation as to how to get the string.
Welp apparently no, it should work like a charm.
Edit: I didn't get the question (which has been edited since then) right.
However because of the extended conversation in the comment section, it'll remain here.

Converting company name to ticker

Hey so I have an excel document that has a mapping of company names to their respective tickers. I currently have this function
def(ticker):
mapping = pd.read_excel('ticker.xlsx',header = 3,parse_cols='A,B')
for index,row in mapping.iterrows():
if ticker.upper() in row['Name'].upper().split():
ticker = row['Ticker']
return ticker
The reason I am using "in" on line 4 instead of "==" is because in the excel document "Apple" is listed as "Apple Inc." and since the user isn't likely to type that I want ticker("apple") to return "AAPL".
In the code above the if statement never gets executed and I was curious on the best possible solution here.
Havnt seen this type of syntax before. Must be the nltk syntax.
That being said I will try to be helpful.
If the In command is the same as SQL then it means exactly equal. Meaning 'Apple' in('Apple Inc') would be false.
You want to do a if('AppleInc like '%Apple%')
or perhaps a .Match using regex. That's about the extent to which I can make suggestions as I don't do python.

Using One String in a Dictionary For an If-Statement (Python 3)

diction1 = {"Pikachu","Harambe","Potato"}
name = input()
if name == diction1:
print("Yay")
^Except it doesn't work.
High schooler here, studying dictionaries. Just wanna know how do I get an input from one variable to match one of the strings in my dictionary to comply with my if-statement.
Sorry, by the way, if this question has been asked already. I'm not too familiar with the terms, so I may have not been able to search the right questions.
First of all it's not a dictionary but set. It's also based on hash-tree. You should check it in the following way:
if name in diction1:
# do stuff

get string with parsing in python list

i have list like this
["<name:john student male age=23 subject=\computer\sience_{20092973}>",
"<name:Ahn professor female age=61 subject=\computer\math_{20092931}>"]
i want to get student using {20092973},{20092931}.
so i want to split to list like this
my expect result 1 is this (input is {20092973})
"student"
my expect result 2 is this (input is {20092931})
"professor"
i already searching... but i can't find.. sorry..
how can i this?
I don't think you should be doing this in the first place. Unlike your toy example, your real problem doesn't involve a string in some clunky format; it involves a Scapy NetworkInterface object. Which has attributes that you can just access directly. You only have to parse it because for some reason you stored its string representation. Just don't do that; store the attributes you actually want when you have them as attributes.
The NetworkInterface object isn't described in the documentation (because it's an implementation detail of the Windows-specific code), but you can interactively inspect it like any other class in Python (e.g., dir(ni) will show you all the attributes), or just look at the source. The values you want are name and win_name. So, instead of print ni, just do something like print '%s,%s' % (ni.name, ni.win_name). Then, parsing the results in some other program will be trivial, instead of a pain in the neck.
Or, better, if you're actually using this in Scapy itself, just make the dict directly out of {ni.win_name: ni.name for ni in nis}. (Or, if you're running Scapy against Python 2.5 or something, dict((ni.win_name, ni.name) for ni in nis).)
But to answer the question as you asked it (maybe you already captured all the data and it's too late to capture new data, so now we're stuck working around your earlier mistakeā€¦), there are three steps to this: (1) Figure out how to parse one of these strings into its component parts. (2) Do that in a loop to build a dict mapping the numbers to the names. (3) Just use the dict for your lookups.
For parsing, I'd use a regular expression. For example:
<name:\S+\s(\S+).*?\{(\d+)\}>
Debuggex Demo
Now, let's build the dict:
r = re.compile(r'<name:\S+\s(\S+).*?\{(\d+)\}>')
matches = (r.match(thing) for thing in things)
d = {match.group(2): match.group(1) for match in matches}
And now:
>>> d['20092973']
'student'
Code:
def grepRole(role, lines):
return [line.split()[1] for line in lines if role in line][0]
l = ["<name:john student male age=23 subject=\computer\sience_{20092973}>",
"<name:Ahn professor female age=61 subject=\compute\math_{20092931}>"]
print(grepRole("{20092973}", l))
print(grepRole("{20092931}", l))
Output:
student
professor
current_list = ["<name:john student male age=23 subject=\computer\sience_{20092973}>", "<name:Ahn professor female age=61 subject=\computer\math_{20092931}>"]
def get_identity(code):
print([row.split(' ')[1] for row in current_list if code in row][0])
get_identity("{20092973}")
regular expression is good ,but for me, a rookie, regular expression is another big problem...

Using Strings to Name Hash Keys?

I'm working through a book called "Head First Programming," and there's a particular part where I'm confused as to why they're doing this.
There doesn't appear to be any reasoning for it, nor any explanation anywhere in the text.
The issue in question is in using multiple-assignment to assign split data from a string into a hash (which doesn't make sense as to why they're using a hash, if you ask me, but that's a separate issue). Here's the example code:
line = "101;Johnny 'wave-boy' Jones;USA;8.32;Fish;21"
s = {}
(s['id'], s['name'], s['country'], s['average'], s['board'], s['age']) = line.split(";")
I understand that this will take the string line and split it up into each named part, but I don't understand why what I think are keys are being named by using a string, when just a few pages prior, they were named like any other variable, without single quotes.
The purpose of the individual parts is to be searched based on an individual element and then printed on screen. For example, being able to search by ID number and then return the entire thing.
The language in question is Python, if that makes any difference. This is rather confusing for me, since I'm trying to learn this stuff on my own.
My personal best guess is that it doesn't make any difference and that it was personal preference on part of the authors, but it bewilders me that they would suddenly change form like that without it having any meaning, and further bothers me that they don't explain it.
EDIT: So I tried printing the id key both with and without single quotes around the name, and it worked perfectly fine, either way. Therefore, I'd have to assume it's a matter of personal preference, but I still would like some info from someone who actually knows what they're doing as to whether it actually makes a difference, in the long run.
EDIT 2: Apparently, it doesn't make any sense as to how my Python interpreter is actually working with what I've given it, so I made a screen capture of it working https://www.youtube.com/watch?v=52GQJEeSwUA
I don't understand why what I think are keys are being named by using a string, when just a few pages prior, they were named like any other variable, without single quotes
The answer is right there. If there's no quote, mydict[s], then s is a variable, and you look up the key in the dict based on what the value of s is.
If it's a string, then you look up literally that key.
So, in your example s[name] won't work as that would try to access the variable name, which is probably not set.
EDIT: So I tried printing the id key both with and without single
quotes around the name, and it worked perfectly fine, either way.
That's just pure luck... There's a built-in function called id:
>>> id
<built-in function id>
Try another name, and you'll see that it won't work.
Actually, as it turns out, for dictionaries (Python's term for hashes) there is a semantic difference between having the quotes there and not.
For example:
s = {}
s['test'] = 1
s['othertest'] = 2
defines a dictionary called s with two keys, 'test' and 'othertest.' However, if I tried to do this instead:
s = {}
s[test] = 1
I'd get a NameError exception, because this would be looking for an undefined variable called test whose value would be used as the key.
If, then, I were to type this into the Python interpreter:
>>> s = {}
>>> s['test'] = 1
>>> s['othertest'] = 2
>>> test = 'othertest'
>>> print s[test]
2
>>> print s['test']
1
you'll see that using test as a key with no quotes uses the value of that variable to look up the associated entry in the dictionary s.
Edit: Now, the REALLY interesting question is why using s[id] gave you what you expected. The keyword "id" is actually a built-in function in Python that gives you a unique id for an object passed as its argument. What in the world the Python interpreter is doing with the expression s[id] is a total mystery to me.
Edit 2: Watching the OP's Youtube video, it's clear that he's staying consistent when assigning and reading the hash about using id or 'id', so there's no issue with the function id as a hash key somehow magically lining up with 'id' as a hash key. That had me kind of worried for a while.

Categories