Function to check if dictionary value is occupied - python

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.

Related

(Python Beginner) Code is only working for the last line in a dictionary

When I apply this code to a dictionary the loop only works for the last list of names in the dictionary, the loop will not work for the first or second set of names...
def function(dictionary, name):
for i in dictionary:
if name == dictionary[i][0]:
result = "the first name is "+str(dictionary[i][0])+" the second name is "+dictionary[i][1]
else:
result = "False"
print(result)
input("name")
function(dict, name)
I assume its an issue with the line 3 but I can not figure it out.
The dictionary would look something like this:
dict = {1: ['john','george'], 2: ['tim','eric'], 3: ['josh','logan']}
This will print the value of result each time through the loop. In your code you were only printing the value of result the last time through the loop. Hence the code only worked on the last element of the dictionary.
def function(dictionary, name):
for i in dictionary:
if name == dictionary[i][0]:
result = "the first name is "+str(dictionary[i][0])+" the second name is "+dictionary[i][1]
print(result)
else:
result = "False"
print(result)
You should use this to iterate (loop) through a dictionary:
for keys, vals in your_dct.items():
if name == vals[0]
#your code here
Your code contains some errors , I have fix them here is your working code :
dict1 = {1: ['john','george'], 2: ['tim','eric'], 3: ['josh','logan']}
def function(dictionary1, name):
for key1,value1 in dictionary1.items():
if name in value1:
result = "the first name is "+value1[0]+" the second name is "+value1[1]
return result
return False
print(function(dict1, input("name")))
First thing , since your values in dict are list so Use in operator to check if first name in values or not , instead of ==
Second thing , use for key,value in dict.items(): instead of indexing
The third thing you are using else return in the same flow so if you search 'josh' it will first return two false and then 'logan' so use return outside of for loop in your code.

Using get() to write a dictionary function more concisely [duplicate]

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.

checking if key's already in dictionary with try except

I'm using a dictionary to count how many times different items appear in a dataset. In the init of the class, I create the property as a dictionary like this
self.number_found = {}
The first time I find any particular item, I would get a KeyError if I try to do this because the item isn't in the dictionary yet
self.number_found[item] = 1
so I ended up creating a function that checks if an entry is already in the dictionary and if not, adds it for the first time
def _count_occurrences(self, item):
try:
#this checks to see if the item's already in the dict
self.number_found[item] = self.number_found[item] + 1
x = self.number_found[item]
except KeyError:
x = 1
#this adds an item if not in the dict
self.number_found[item] = x
return x
However, this is not working as intended if I find a second occurrence of an item in a dataset.
Let's say there are two 'elephant' in my dataset. When I print self.number_found to the console this is what I get
{'elephant': 1}
{'elephant': None}
and I get this error when adding the second occurrence
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
Question: what's the right way to check if the key's already in the dictionary (with an explanation as to why the 1 is changing to a None)
You can use a defaultdict:
from collections import defaultdict
self.number_found = defaultdict(int)
The first time an item is accessed, its value will take a default of 0
A None is returned because you're not returning anything in your try branch
The return at the end of the except block must be moved out. That way, x is returned for both cases
class C(object):
def __init__(self):
self.number_found = {}
def _count_occurrences(self, item):
try:
#this checks to see if the item's already in the dict
self.number_found[item] = self.number_found[item] + 1
x = self.number_found[item]
except KeyError:
x = 1
#this adds an item if not in the dict
self.number_found[item] = x
return x
c = C()
r = c._count_occurrences('elephant')
print r
print c.number_found
r = c._count_occurrences('elephant')
print r
print c.number_found
Here is a test run first with outdented return, then with it where you have it in your OP:
jcg#jcg:~/code/python/stack_overflow$ python number_found.py
1
{'elephant': 1}
2
{'elephant': 2}
jcg#jcg:~/code/python/stack_overflow$ python number_found.py
1
{'elephant': 1}
None
{'elephant': 2}
As you can see, the second version returns None since there is no return from the _count_occurrences try block

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")

(Dictionary) storing keys with x,y in Python

What I am trying to do is to store an x,y value with a key. For example, in my case, I need it so that once any x,y has reached the value of 3, some process happens.
Here is what I have tried: However, this gives me an error, as I am unable to store lists within dictionaries.
dictionary= {}
player = [0,0]
def Checking():
if player in dictionary:
dictionary[[player]] +=1
print("repopulate", dictionary)
else:
dictionary[player] = 0
print(dictionary)
if dictionary.get(player) >= 3:
print("It is done!")
EDIT:
Sorry about the lack of clarity in the question. The player variable is the user input of where the user wishes to move within the x,y given. There are multiple treasures, and if the user is to chose a position x,y which is the same as a treasure x,y; then +1 should be added to that treasure. Once a treasure reaches 3, it should be diminished.
I think you want to use player as your key, and the count as the value of that key:
>>> treasure_hits = {}
>>> player = (0,0)
>>> try:
... treasure_hits[player] += 1
... except KeyError:
... treasure_hits[player] = 0
...
>>> treasure_hits
{(0, 0): 0}
>>>
>>> try:
... treasure_hits[player] += 1
... except KeyError:
... treasure_hits[player] = 0
...
>>> treasure_hits
{(0, 0): 1}
>>>
Making treasure_hits a tuple instead of a list allows it to be used as a key since it is immutable
If you save you list x,y in the dictionary like this, that also depends on your condition when you want to change the values you have to iterate through the list.
treasureHits = {}
player = [0,0]
def myFunction():
treasureHits["key"]=[p+1 for p in player]
print treasureHits["key"]
myFunction()
That's what I understand from your question.
So the easiest way to do this is to call str() on the player variable. This will turn the list into a string. You need to do this because dictionaries cannot use lists as keys. So try the following: treasureHits[str(player)]
Note thought that this is usually not recommended because you will have very unusual keys and if anyone else will be editing your code it could be confusing. Make sure to leave plenty of comments in your code!

Categories