How can a variable check through an empty dictionary - python

content_ratings = {}
ratings = ['4+', '4+', '4+', '9+', '9+', '12+', '17+']
for c_rating in ratings:
# why is the variable c_rating checking the empty dictionary
if c_rating in content_ratings:
content_ratings[c_rating] += 1
else:
content_ratings[c_rating] = 1
print(content_ratings)
print('Final dictionary:')
print(content_ratings)

#Yuppie, The if is used for verifying if the rating has already been added to the dictionary in a previous loop. If so, it will increment the current value. Otherwise, it will basically initialize it to 1.

Same as eespejel said, c_ratings is the variable that is there to place hold a certain item in the list, going from the first item to the last. Then you do something with the c_ratings variable, like test if c_ratings is already inside the dictionary content_ratings. IF it is already there, increment that score by one. ELSE (if all previous ifs and elifs werent satisfied, set that value to one in the dictionary. This is why when the dictionary is empty, the ELSE is being run, because c_ratings is definitely not in the dictionary, when it is empty.

Related

Unable to add to blank list

I am working on a program that can be used to add a given value say a car dealership with the cars it owns:
for example
car_storage = []
def add_cars(dealership, car):
for items in car_storage:
for values in items:
if dealership in items:
#Adds car whether it exists or not in list
items.append(car)
return
#If the dealership does not exist it is created and added to the list
else:
items.append([dealership, car])
return
add_cars("Manchester", "Mini")
add_cars("London", "Toyota")
add_cars("London", "BMW")
add_cars("London", "BMW")
#Desired output
[["Nottingham", "Audi"],["Manchester","Mini"],["London", "Lorry", "BMW", "BMW"]]
However, my code never adds to the list, where am I going wrong?
The issue with your code as #juanpa.arrivillaga said is that the before you add the first item the list car_dealership is empty so nothing in your function executes.
Your approach however is almost correct, Python supports else keyword with for loops. What it means is, if the for loop ran without breaking (no break statements) the else statement is called. For example
for i in range(1, 4):
if i==2:
break
else: # Not executed as there is a break
# if we remove the break the else will run
print("No Break")
Now similarly in your code. you can use the same concept.
def add_cars(dealership, car):
for items in car_storage:
for values in items:
if dealership in items:
#Adds car whether it exists or not in list
items.append(car)
return
#If the dealership does not exist it is created and added to the list
else:
car_storage.append([dealership, car])
Which is very similar to your original code except the indentation level on the else part.
Now in this case since you're returning and not breaking you can even get away with removing the else entirely since the function will never reach there
def add_cars(dealership, car):
for items in car_storage:
for values in items:
if dealership in items:
#Adds car whether it exists or not in list
items.append(car)
return
#If the dealership does not exist it is created and added to the list
car_storage.append([dealership, car])

Re-initialising a list

I have a list of dictionaries that is initialised by a call to a function with:
new = {'device_id':name,'device_mac':mac, 'device_ttl':ttl}
dev[0] = new
Thereafter, new entries are appended with:
dev.append(new)
Each dictionary has a time to live (TTL). Once that is reached the dictionary is removed:
for i in dev:
if (i['device_ttl'] == 0):
dev.remove(i)
This all seems fine until the list is completely empty. If I then try and add a new entry with:
dev[0] = new
again, I get a 'list index out of range' error.
I've tried changing the original initialisation with an append to an empty list, but that bombs out immediately with a KeyError: device_id.
The entire function that adds entries is:
# Adds a new device to the list of known devices.
def add_device(dev, num, name, mac, ttl):
new = {'device_id':name,'device_mac':mac, 'device_ttl':ttl}
if (num == 0):
#dev.append(new)
#dev = new
dev[0] = new
else:
dev.append(new)
return (num + 1)
The essential part of the main routine is:
devices = [{}] # Empty list.
num_devices = 0
# Code that determines whether to add to the list or not
num_devices = add_device(devices, num_devices,\
name_long, mac_address, ttl_n)
I don't understand why initialising by appending to an empty list is problematic, nor why what does work to initialise, doesn't work when the list is empty. It is created as empty in the first place!
Is there a better way to initialise or append to an empty list?
The answer was to not declare an empty list of dictionaries ,but just an empty list. A number of respondents pointed out the error but did not elucidate an answer.
Declaring an empty list of dictionaries with:
devices=[{}]
Creates an empty list with an empty dictionary. Assigning the first dictionary with:
dev[0] = new
just replaced the empty dictionary. Hence why the same assignment doesn't work when the list is emptied.
The correct initialisation was to just declare:
devices = []
Adding any dictionary after that, including the first one, is by using an append in the function:
dev.append(new)
Thanks for all of the pointers. I found the answer by switching IDE from Atom to Idle for testing. I have to use Atom as it is the only IDE with the PyCom plugin. Idle flagged the error almost immediately.

how to subtract a value of a key in python dictionary

I'm learning python and I'm trying to use this function I built and its not working. The function is not changing a single value in the dictionary as it is working now, although it should. I'd like to get some help
def delete_product(diction):
product_to_delete = raw_input()
for key,value in diction.items():
if key == product_to_delete:
value = value - 1
if (value == 0):
del diction[key]
print "removed"
raw_input()
print "we couldnt remove the product because it does not exist"
raw_input()
Mistake in this code snippet:
value = value - 1
if (value == 0):
del diction[key]
Instead of modifying value in the dictionary, you are only modifying local value. So, this function will delete the required entry only when value happens to be 1.
You can modify it as follows or any variation of it:
if value == 1:
del diction[key]
break
else:
diction[key] = value - 1
Moreover, please note that you have to break out of the for loop once the entry is deleted from the dictionary. If you modify the dictionary while you are iterating it, the iterator will not work after that. If you want to delete multiple keys in one iteration, first get list of all keys to be deleted within the loop and delete after the loop.

How to dynamically append to array in dict?

This has taken me over a day of trial and error. I am trying to keep a dictionary of queries and their respective matches in a search. My problem is that there can be one or more matches. My current solution is:
match5[query_site] will already have the first match but if it finds another match it will append it using the code below.
temp5=[] #temporary variable to create array
if isinstance(match5[query_site],list): #check if already a list
temp5.extend(match5[query_site])
temp5.append(match_site)
else:
temp5.append(match5[query_site])
match5[query_site]=temp5 #add new location
That if statement is literally to prevent extend converting my str element into an array of letters. If I try to initialize the first match as a single element array I get None if I try to directly append. I feel like there should be a more pythonic method to achieve this without a temporary variable and conditional statement.
Update: Here is an example of my output when it works
5'flank: ['8_73793824', '6_133347883', '4_167491131', '18_535703', '14_48370386']
3'flank: X_11731384
There's 5 matches for my "5'flank" and only 1 match for my "3'flank".
So what about this:
if query_site not in match5: # here for the first time
match5[query_site] = [match_site]
elif isinstance(match5[query_site], str): # was already here, a single occurrence
match5[query_site] = [match5[query_site], match_site] # make it a list of strings
else: # already a list, so just append
match5[query_site].append(match_site)
I like using setdefault() for cases like this.
temp5 = match5.setdefault(query_site, [])
temp5.append(match_site)
It's sort of like get() in that it returns an existing value if the key exists but you can provide a default value. The difference is that if the key doesn't exist already setdefault inserts the default value into the dict.
This is all you need to do
if query_site not in match5:
match5[query_site] = []
temp5 = match5[query_site]
temp5.append(match_site)
You could also do
temp5 = match5.setdefault(query_site, [])
temp5.append(match_site)
Assuming match5 is a dictionary, what about this:
if query_site not in match5: # first match ever
match5[query_site] = [match_site]
else: # entry already there, just append
match5[query_site].append(temp5)
Make the entries of the dictionary to be always a list, and just append to it.

How to check if a dictionary value is equal to a variable's value

I'm creating a Python library for creating simple text-based games, and I need to compare an item in a dictionary's value to a variable's value.
EDIT: I have a dictionary for items that exist in a world.
ITEMS_IN_WORLD = {"Key": "Hotel", "Stone": "Park"}
I also have a variable that contains the player's current 'location'.
CURRENT_LOCATION = "Store"
What I need to do is make the program check if CURRENT_LOCATION is equal to one of the dictionary's values. (Hotel, Park, etc.)
for item, location in ITEMS_IN_WORLD.iteritems():
if (CURRENT_LOCATION==location):
print ("Found!") #Or whatever you intend to do

Categories