Using dictionary for conditional assignment - python

How can I use dictionary as a conditional statement to change the value of the variable?
for example:
a = 20
dicta = {10:3, 20:2, 30:1}
#compare using first pair as the value of a, such that:
if a=10: assign a=3
if a=20: assign a=2
if a=30: assign a=1
Thankyou!

If you can be sure that the value of a is actually a key in the dict:
a = dicta[a]
or to have an additional check:
if a in dicta:
a = dicta[a]
else:
print("error, value {} not in dictionary".format(a))

Try this:
a = 20
for k, v in dicta.items():
if k == a:
a = v
break

Related

prevent OrderedDict from splitting single string value into characters during iteration

I would like to make an OrderedDict with a string for each key and a list of strings for each value.
from collections import OrderedDict
# Compare a dict with an OrderedDict
someDict = dict(a = ["foo","bar"], b = ["baz"])
someOrderedDict = OrderedDict([("a",("foo","bar")),("b",("baz"))])
I need to iterate over this dictionary with access to both the key and the values. On a vanilla dictionary, this is simply:
for k,v in someDict.items():
for eachv in v:
print("do something with key = " + k + " and value = " + eachv)
# returns the desired output:
# do something with key = a and value = foo
# do something with key = a and value = bar
# do something with key = b and value = baz
(If this can be done in a comprehension, please enlighten me -- I couldn't figure out how to do without losing access to the key.)
When I try this on the OrderedDict I get:
for k,v in someOrderedDict.items():
for eachv in v:
print("do something with key = " + k + " and value = " + eachv)
# results in undesirable splitting of value "baz" into ["b","a","z"]:
# do something with key = a and value = foo
# do something with key = a and value = bar
# do something with key = b and value = b
# do something with key = b and value = a
# do something with key = b and value = z
What am I doing wrong?
This is because you're assigning a string (("baz")) to the b key, rather than a tuple (("baz",)) or list of strings.
Instead of
someOrderedDict = OrderedDict([("a",("foo","bar")),("b",("baz"))])
try
someOrderedDict = OrderedDict([("a",("foo","bar")),("b",("baz",))])
(Note the new comma.)
You can add a , after "baz" so it can get interpreted as a tuple instead of a single str during the for loop:
someOrderedDict = OrderedDict([("a",("foo","bar")),("b",("baz",))])
Then, iteration works fine grabbing the single element of the tuple baz:
for k,v in someOrderedDict.items():
for eachv in v:
print("do something with key = " + k + " and value = " + eachv)
do something with key = b and value = baz
do something with key = a and value = foo
do something with key = a and value = bar
The same could be achieved by wrapping the values in []:
[("a", ["foo","bar"]),("b", ["baz"])]
Even better, if you already have the dictionary available, just expand (unpack) the dictionary someDict in someOrderedDict by utilizing the ** syntax:
someOrderedDict = OrderedDict(**someDict)
it works equally well and looks much more compact and clean.

Printing a dictionary value of a function in another function

I'm trying to write a looping function that prompts the user to enter a key from the first function and if it is is a key then it prints its value. If the word entered is not in the dictionary it returns "No entry".
What I have so far.
def read_ticker():
c = {}
with open('tickers.csv') as f:
for line in f:
items = [item.strip('"').strip() for item in line.split(",")]
c[items[0]] = items[1:]
print(c)
read_ticker()
d = read_ticker()
def ticker():
x = input('Ticker: ')
if x in d:
return x[c]
else:
return 'No entry'
ticker()
How can I return the value of the key entered in the second function?
You never return your dictionary in read_ticker, and it's unclear why you're calling the function twice.
Where print(c) is put return c.
And I think you want to index the dict instead of indexing the input.
Also, what is c that you're indexing with? This is undefined. I'm assuming this is meant to be the dictionary as defined in read_ticker. In which case you want d[x].
The dictionary c isn't global, although you could define it to be, so you can't access it in your other function by c (ignoring that the indexing is backwards even if possible). Instead, since the dictionary is local to the function read_ticker and modified there we return the dictionary and store it in the variable d.
Your read_ticker() function should return c:
def read_ticker():
c = {}
with open('tickers.csv') as f:
for line in f:
items = [item.strip('"').strip() for item in line.split(",")]
c[items[0]] = items[1:]
print(c)
return c
and then you can modify your ticker function as follows:
def ticker():
x = input('Ticker: ')
if x in d.keys():
return d[x]
else:
return 'No entry'
Your ticker function can use get, which allows you to give a value if the key doesn't exist, like this:
def ticker():
x = input('Ticker: ')
return d.get(x, "No entry")

Increasing values in a dictionary?

Is there a function which can take in a dictionary and modify the dictionary by increasing only the values in it by 1?
i.e
f({'1':0.3, '11':2, '111':{'a':7, 't':2}})
becomes
{'1':1.3, '11':3, '111':{'a':8, 't':3}}
and
f({'a':{'b':{'c':5}}})
becomes
{'a':{'b':{'c':6}}}
Thanks!
Not the best...
def incr(d):
try:
return d + 1
except TypeError: # test the type rather catch error
return g_incr(d)
except:
return 0
def g_incr(d):
return {k:incr(v) for k, v in d.items()}
test = {'1':0.3, '11':2, '111':{'a':7, 't':2}}
print g_incr(test)
I think you should try this;
def increment(dict):
return {k:v+1 for k,v in dict.items()}
result = increment()
print result

None value in python dictionary

Is it possible to check none value in dict
dict = {'a':'None','b':'12345','c':'None'}
My code
for k,v in d.items():
if d[k] != None:
print "good"
else:
print "Bad
Prints three good after executing above code snippet.
good
good
good
Required:If value is None than not printing good for dict key a and c.
Your none values are actually strings in your dictionary.
You can check for 'None'
or use actual python None value.
d = {'a':None,'b':'12345','c':None}
for k,v in d.items():
if d[k] is None:
print "good"
else:
print "Bad"
prints "good" 2 times
Or if you Have to use your current dictionary just change your check to look for 'None'
additionally dict is a python built in type so it is a good idea not to name variables dict
Define your dictionary with
d = {'a': None}
rather than
d = {'a': 'None'}
In the latter case, 'None' is just a string, not Python's None type. Also, test for None with the identity operator is:
for key, value in d.iteritems():
if value is None:
print "None found!"
def none_in_dict(d):
for _, value in d.items():
if value is None:
return True
return False
And the use is:
if none_in_dict(my_dict):
logger.error(my_err_msg)
Instead of using "if value is None" you can simply use
d = {'a':None, 'b':'12345', 'c':None, 'd':'None'}
for k, v in d.items():
if v:
print("good")
else:
print("bad")
"if v" will be True if there is any kind of value except None. Hence you don't have to explicitly use None keyword in if condition (if v is None).
Result:
bad
good
bad
good
In last case the value for key 'd' is 'None' - as a string not python value None

Python dictionary get method in assignment [duplicate]

This question already has an answer here:
Dictionary syntax error "can't assign to function call"
(1 answer)
Closed 9 months ago.
All,
I'm looping over a dictionary and counting the values that occur. To do this, I'm using the get method in the assignment statement for another dictionary. This returns a syntax error "can't assign to function call"
counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
for key,value in mydict.iteritems():
counts(value[1]) = counts.get(value[1], 0) + 1
Why would the assignment try to point to the function, rather than the return value?
counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
for key,value in mydict.iteritems():
counts[value[1]] = counts.get(value[1], 0) + 1
You need brackets, not parenthesis, to get an item from a dictionary.
Also, You're doing this the hard way.
from collections import defaultdict
# automatically start each count at zero
counts = defaultdict(int)
# we only need the values, not the keys
for value in mydict.itervalues():
# add one to the count for this item
counts[value[1]] += 1
or
# only on Python 2.7 or newer
from collections import Counter
counts = Counter(value[1] for value in mydict.itervalues())
Instead of counts(value[1]) = ... you want counts[value[1]] = ....
Change this:
counts(value[1])
to this:
counts[value[1]]
Code looks like this:
counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
for key, value in mydict.iteritems():
counts[value[1]] = counts.get(value[1], 0) + 1
counts[value[1]] = counts.get(value[1], 0) + 1
should be
counts[value[1]] = counts.get(value[1], 0) + 1

Categories