Build dict in loop. Python - python

I'm trying to find out what I'm doing wrong here.
I'm trying to build a simple ordered dict inside a loop.
Heres the code:
dTabs = OrderedDict()
for iFolder, folder in enumerate(mtd.GroupedTables):
if folder.Count > 0:
dTabs[folder.Name] = OrderedDict()
for item in folder:
table = item.Table
dTabs[folder.Name] = table.Name
print dTabs
this is the output:
OrderedDict([('YouthSportsTrustSportParents_P', 'KYS_Q8_YouthSportsTrustSportParents_P'), ('YouthSportsTrustSportParents_PM', 'KYS_Q8_YouthSportsTrustSportParents_PM')])
there should be six more values for each key...but im only seeing the last two values for each key.
What am i doing wrong here?

Your inner loop assigns in the same location over and over
dTabs = OrderedDict()
for iFolder, folder in enumerate(mtd.GroupedTables):
if folder.Count > 0:
dTabs[folder.Name] = OrderedDict()
for item in folder:
table = item.Table
dTabs[folder.Name] = table.Name # same location is being updated
print dTabs
you need a list like data structure to hold each "table.Name"
dTabs = OrderedDict()
for iFolder, folder in enumerate(mtd.GroupedTables):
if folder.Count > 0:
dTabs[folder.Name] = []
for item in folder:
table = item.Table
dTabs[folder.Name].append(table.Name)
print dTabs

Your inner for loop:
for item in folder:
table = item.Table
dTabs[folder.Name] = table.Name
overwrites the value of dTabs[folder.Name] each time it goes through-- that is, for each item in folder, folder.Name is the same, and each subsequent item overwrites the last one's entry because it has the same key! I think that you think that you can have more than one value per key, which is not true. Try appending onto the current value for the key, instead of replacing it.

Related

dictionary being replaced and I am not sure why it is happening?

I have some code which is something along the lines of
storage = {}
for index, n in enumerate(dates):
if n in specific_dates:
for i in a_list:
my_dict[i] = {}
my_dict[i]["somthing"] = value
my_dict[i]["somthing2"] = value_2
else:
#print(storage[dates[index - 1]["my_dict"][i]["somthing"])
for i in a_list:
my_dict[i] = {}
my_dict[i][somthing] = different_value - storage[dates[index - 1]["my_dict"][i]["somthing"]
my_dict[i]["somthing2"] = different_value_2
storage[n]["my_dict"] = my_dict
The first pass will initiate the code in if n in specific_dates: the second pass goes to for i in a_list:
Essentially the code is getting a value set on specific dates and this value is then used for nonspecific dates that occur after the specific date until the next specific date overrides that value. However, at every date, i save a dictionary of values within a master dictionary called storage.
I found the problem which is when I print my_dict on the second pass my_dict[i] is literally an empty dictionary whereas prior to that loop it was filled. Where I have put the commented-out print line it would print value. I have fixed this by changing storage[n]["my_dict"] = my_dict to storage[n]["my_dict"] = my_dict.copy() and can now access value.
However, I do not really understand why this didnt work how I expected in the first place as I thought by assigning my_dict to storage it was creating new memory.
I was hoping someone could explain why this is happening and why storage[dates[index - 1]["my_dict"][i]["somthing"] doesn't create a new space in memory if that is indeed what is happening.

Adding value of every item in dict

I'm trying to add every value under "title" from a dictionary to a list but i always get KeyError: 'title'.
list = []
q = input("Search:")
search = SearchVideos(q, mode = 'dict')
dictt = (search.result())
print(dictt)
for i in dictt:
list.append(dictt['title'])
you have a few problems here.
First, you're not accessing the right value. It looks like dictt has only one key: search_result and you should iterate on it's value.
In addition, list.append(value) will not add the value to a list. you need to make a list and then do new_list.append(value).
lastly you didn't use i in your loop.
It should look like this:
new_list = []
for item in dictt['search_result']:
new_list.append(item['title'])

Python for loop appends only the last list as value

I am looping through a directory and want to get all files in a folder stored as list in a dictionary, where each key is a folder and the list of files the value.
The first print in the loop shows exactly the output I am expecting.
However the second print shows empty values.
The third print after initialization of the class shows the list of the last subfolder as value for every key.
What am I overlooking or doing wrong?
class FileAndFolderHandling() :
folders_and_files = dict()
def __init__(self) :
self.getSubfolderAndImageFileNames()
def getSubfolderAndImageFileNames(self) :
subfolder = ""
files_in_subfolder = []
for filename in glob.iglob('X:\\Some_Directory\\**\\*.tif', recursive=True) :
if not subfolder == os.path.dirname(filename) and not subfolder == "" :
print(subfolder + " / / " + str(files_in_subfolder))
self.folders_and_files[subfolder] = files_in_subfolder
files_in_subfolder.clear()
print(self.folders_and_files)
subfolder = os.path.dirname(filename) # new subfolder
files_in_subfolder.append(os.path.basename(filename))
folder_content = FileAndFolderHandling()
print(folder_content.folders_and_files)
It seems like the problem you have is that you are actually using always the same list.
Defining files_in_subfolder = [] creates a list and assigns a pointer to that list in the variable you just defined. So what happens then is that when you assign self.folders_and_files[subfolder] = files_in_subfolder you are only storing the pointer to your list (which is the same in every iteration) in the dictionary and not the actual list.
Later, when you do files_in_subfolder.clear() you are clearing the list to which that pointer was pointing to, and therefore to all the entries of the dictionary (as it was always the same list).
To solve this, I would recommend you to create a new list for each different entry in your dictionary, instead of clearing it for each iteration. This is, move the definition of files_in_subfolder from outside the loop to inside of it.
Hope it helps!
It sounds like you are after defaultdict.
I adapted your code like this:
import glob, os
from collections import defaultdict
class FileAndFolderHandling() :
folders_and_files = defaultdict(list)
def __init__(self) :
self.getSubfolderAndImageFileNames()
def getSubfolderAndImageFileNames(self) :
for filename in glob.iglob(r'C:\Temp\T\**\*.txt', recursive=True) :
# print(filename)
subfolder = os.path.dirname(filename)
self.folders_and_files[subfolder].append(os.path.basename(filename))
folder_content = FileAndFolderHandling()
print(dict(folder_content.folders_and_files))
Output:
{'C:\\Temp\\T': ['X.txt'], 'C:\\Temp\\T\\X': ['X1.txt', 'X2.txt'], 'C:\\Temp\\T\\X2': ['X1.txt']}
The defaultdict(list) makes a new list for every new key added. This is what you seems to want to happen in your code.
You are clearing the array, from what I see...
files_in_subfolder.clear()
Remove that and make sure your value gets added to the folders_and_files variable before any clear operation.

A list of structure with Python

I am new in python,
I want work with structured lists:
class X_ItemSet: # Structure of an Item
Item = []
ItemTID = []
oneItem = X_ItemSet #one instance of X_ItemSet
ListTID = [X_ItemSet] #Liste of X_ItemSet
oneItem.Item.append(1)
oneItem.ItemTID.append("a")
ListTID.append(oneItem)
del oneItem[:]
my problem is when deleting oneItem also ListTID will be empty
what should i do to keep values in ListTID when deleting oneItem?

How to *append* a text to a database file opened with shelve?

After we create a database file using shelve.open and then close the program, if we run the code again, but with different input(s), it actually replaces the text instead of appending it.
How may I change this behavior?
For example:
db = shelve.open('store')
db['some variable'] = some value
db['another variable'] = another value
db.close()
And now when we write the same code but with different values for the same variable, we replace the previous value instead of appending the values to it. How can I change that?
Assuming your values are lists:
Use db = shelve.open('store',writeback=True) and then append the value to the same key.
Since your code does not open 'store' with writeback=True you
must assign a variable the value of the key, temp = db['some variable'], which would be
some value, and then append that variable, temp.append(another
value), and then reassign that keys value, db['some variable'] =
temp.
Should not your third line of code be db['some variable'] = another value' in order to replace the value?
Edit: Other possible meaning of question?
Do you mean you want to load the database into your object and continue to use your "UI" code to edit it after closing the program? If so then you can do something like:
class Update_MyStore(MyStore):
def __init__(self, store):
db = shelve.open(store)
for i in db:
setattr(self, i, db[i])
self.items()
self.store_in_db()
Update_MyStore('store')
Edit: Another option to update, if that is the case, if you want to add or update specific items:
while True:
store = shelve.open('store',writeback = True)
Item = input('Enter an item: ').capitalize() #I prefer str(raw_input('Question '))
if not Item or Item == 'Break':
break
store['item_quantity'][Item] = int(input(('Enter the number of {0} available in the store: ').format(Item)))
store['item_rate'][Item] = float(input(('Enter the rate of {0}: ').format(Item)))
store.sync()
store.close()

Categories

Resources