This question already has answers here:
How to add or increment a dictionary entry?
(6 answers)
Closed 6 years ago.
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
print(histogram('brontosaurus'))
So I am asked to use 'get' method to write the function more concisely. It says I should be able to remove the 'if' statement. I tried different things but I just need to see an example before I understand... Please provide example code thank you very much!
Update: I have researched it, I understand 'what' get is but I am having trouble using it in this case. I don't know how to modify this function... This is where I am stuck.
In Python, dict.get(k,v) will search the dictionary for the key k and return it. However, if k does not exist in the dictionary, instead of raising a KeyError like d[k] does and potentially crashing the program, it will instead return the default value provided, v. Calling get(k) without specifying a default value v will return None.
With this said, it's a trivial matter to remove the if statement:
def histogram(s):
d = dict()
for c in s:
d[c] = d.get(c,0) + 1
return d
If d[c] does not exist, d.get(c,0) will in turn return 0, the provided default value. If d[c] does exist, d.get(c,0) will return the stored value. Therefore, if a key is not yet in the dictionary, d[c] is set to 0 + 1 which is, of course, 1. The next time that particular key is get-ed, get will return the stored value 1 instead, then add 1 and reassign, and so on.
Related
I'm trying to make a function to check whether a value added to a dictionary already exists.
If a value is already in the dictionary, it should print "Occupied" and not add the value to the existing key.
I have tried to get it to not append when the new input is similar, but it still adds the new input even though it is the same as the previous.
For example, if I add input_v as "Hi" --> XO = {'key': ["Hi"]}
If I were to put in "Hi" again, I then want it to say "Occupied", but as of right now it still adds to the dictionary.
XO = {'key': []}
def check_values(input_v):
value = input_v
print(XO)
if value in XO.values():
print("Occupied")
else:
XO['key'].append(value)
The issue is in the way you referenced the value of the 'key'. Use this:
XO = {'key': []}
def check_values(input_v):
value = input_v
global XO
#print(XO)
if value in XO['key']:
print("Occupied")
else:
XO['key'].append(value)
#print(XO)
d = dict()
for c in a:
if c not in d:
d[c] = 1
else:
print("Occupied")
Would this work? a is a list in this example.
This question already has answers here:
How to check if a dictionary is empty?
(9 answers)
Closed 1 year ago.
in python:
dic = {} #start with an empty list
After this line, I did a series of command to add things to the dic. But there is also a situation where nothing is added. Then, I need to use the value in the dic.
a = min(dic, key=dic.get)
if there is nothing in the dic, it will give me an error:
ValueError: min() arg is an empty sequence I don't need an output for a if dic is empty, so I then attempted to use the if statement to get away:
if dic == None:
pass
else:
a = min(dic, key=dic.get)
but this will still give me the same error. Is there a way to skip this line of codea = min(dic, key=dic.get)when dic = {}?
The dic is of the <class dict> whereas the None object is of the <class 'Nonetype'>.
So the given expression dic == Nonewill always return False.
Instead change it to dic == {} or len(dic) == 0 or simply dic.
An empty dictionary will usually evaluate to False.
if dic:
pass
else:
a = min(dic, key=dic.get)
Try changing the logic to:
if len(dic) == 0:
pass
else:
a = min(dic, key=dic.get)
You current code skips over the pass block because even if the dict dic is empty, it is not None, there's a bunch of ways to check emptiness of a dict, personally, I'm a fan of checking the len as above but there are other way such as on this page.
I need help creating a function that goes through a given dictionary. The value associated with that key may be another key to the dictionary. i need the function to keep looking up the keys until it reaches a key that has no associated value.
def follow_me(d, s):
while d:
if s in d:
return d[s]
I can return the value in the dictionary that s equals to but I've no idea how to iterate through it until I get a value that has no associated value. So I can get the value that badger is doe, but how do I iterate through the dictionary until I get fox and then fox to hen etc.
d = {'badger':'doe', 'doe':'fox', 'fox':'hen','hen':'flea',
'sparrow':'spider', 'zebra':'lion', 'lion':'zebra'}
print(follow_me(d, 'badger'))
print(follow_me(d, 'fox'))
print(follow_me(d, 'sparrow'))
print(follow_me(d, 'zebra'))
print(follow_me(d, 'aardvark'))
and this is what I currently have of the function that makes sense to me because everything else I've tried is just wrong.
def follow_me(d, s):
while d:
if s in d:
return d[s]
and the output needs to be:
flea
flea
spider
aardvark
but my code right now is producing:
doe
hen
spider
lion
To extend on the other answers, which are still valid. If you have a very large dictionary then using key not in dic.keys() or k in d iterates through all keys every loop.
To go around this, one can use a try catch:
def follow_me(dic, key):
while True:
if key not in dic.keys():
return key
key = dic[key]
def follow_me2(dic, key):
try:
while True:
key = dic[key]
except Exception as e:
return key
import time
d = { i: (i+1) for i in range(10000000) }
start = time.time()
follow_me(d, 0)
print("Using 'in' takes", time.time() - start,"s")
start = time.time()
follow_me2(d, 0)
print("Using 'try' takes", time.time() - start,"s")
gives the output:
Using 'in' takes 2.476428747177124 s
Using 'try' takes 0.9100546836853027 s
I think this is what you are looking for, though your problem description is very unclear:
def follow_me(d, k):
while k in d:
k = d[k]
return k
Note that the loop in this function will run forever if there is a cycle between keys and values in your dictionary. Your example has one between 'lion' and 'zebra', and it's not entirely clear how you intend such a cycle to be broken. If you want to expand each key only once, you could handle it by keeping track of the values you've seen so far in a set:
def follow_me(d, k):
seen = set()
while k in d and k not in seen:
seen.add(k)
k = d[k]
return k
This will return whichever key in the cycle you reach first (so follow_me(d, 'zebra') with your example dictionary will return 'zebra' after going zebra => lion => zebra). If you want some other outcome, you'd need different logic and it might be tricky to do.
If you request a key that's not in the dictionary (like 'aardvark' in your example), the requested key will be returned immediately. You could add special handling for the first key you look up, but it would again make things more complicated.
Considering the existence of infinite loops this has to be handled. Your description isn't clear about what should happen in this case.
def follow_me(d, key):
visited_keys = []
while key not in visited_keys and d[key]:
visited_keys.append(key)
key = d[key]
if not d[key]:
return key
return "this hunt has no end"
I've come across a question that I was confused about so decided to look it up. However, I'm a bit confused as to what some of the functions do in the code. The question was 'write a function to get rid of duplicate letters'
def remove_duplicates(s):
result = ""
dic = {}
for i in s:
if i not in dic:
result+=i
if ord(i.lower()) >= ord('a') and ord(i.lower()) <= ord('z'):
dic[i] = 1
return result
print(remove_duplicates("bookkeeper"))
I'm a bit confused as to what the purpose of the result = "" and dic = {}? I've never seen this before so no idea how it works.
And what does result+=i mean? And finally I have absolutely no idea what's going in the if ord line. Ord is something I just learned an hour ago so I have no idea how it's interacting with i.lower and 'a' / 'z'.
result = "" creates a variable named result and initializes it to a blank string.
dic = {} creates a variable named dic and initializes it to an empty dictionary. (Dictionaries are special Python objects.)
result += i is shorthand for result = result + i.
The if ord line is ensuring that i is a letter between A and Z. (Although this seems a very roundabout way to do it.)
Perhaps you should spend some time with a basic Python tutorial?
result = "" and dic = {} initallize the variables result as an empty string ans dic as a dictionary.
result+=i mean === result = result + i
About the ord() it checks if i.lower is in "range" of a - z
This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 7 months ago.
My very simple python function is returning None at the end of it and I'm not sure quite why. I've looked at some other posts and still can't figure it out.
Here is my code:
def printmult(n):
i = 1
while i <= 10:
print (n * i, end = ' ')
i += 1
print(printmult(30))
Because in Python, every function returns a value, and None is what is returned if you don't explicitly specify something else.
What exactly did you expect print(printmult(30)) to do? You've asked it to evaluate printmult(30), and then print whatever results from that. Something has to result from it, right? Or were you maybe expecting some kind of exception to be raised?
Please be sure you understand that printing and returning are not the same thing.
You are not returning anything in the function printmult, therefore when you print the result of printmult(30) it will be None (this is the default value returned when a function doesn't return anything explictly).
Since your method have a print statement inside and it's not supposed to return something (usually when a method names is something like printSomething(), it doesn't return anything), you should call it as:
printmult(30)
not
print(printmult(30))
The other answers have done a good job of pointing out where the error is, i.e. you need to understand that printing and returning are not the same. If you want your function to return a value that you can then print or store in a variable, you want something like this:
def returnmult(n):
i = 1
result_string = ''
while i <= 10:
result_string += str(n * i) + ' '
i += 1
return result_string
print(returnmult(30))
def printmult(n):
i = 1
while i <= 10:
print (n * i, end = ' ')
i += 1
printmult(30)
The issue was that you were printing the return value of a function that returns nothing, which would print None
I came from Ruby as well and it seems strange at first.
If you print something that has a print statement in it, the last thing it returns is None.
If you just returned the values and then invoked a print on the function it would not output None.
Hope this helps :)