Вопрос

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top