Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionaries
#1
I need help with looping through the values of a dictionary.
def combine_dict(year_dict, headers):
    borough={}
    i=0
    for x in year_dict:
        while i<len(headers)-1:
            borough[headers[i+1]]=year_dict[x][i]
            i+=1
    for y in nums:
        nums[y]=borough
    return(nums)  

pop_dict= combine_dict(pop_dict, pop_headers)
pprint(pop_dict)



The output only takes the first row of the dictionary instead of the entire dictionary. For example, Year 1800 should have different values for each borough. What's wrong with my code?
Output:
{'1790': {'Bronx': '1781', 'Brooklyn': '4549', 'Manhattan': '33131', 'Queens': '6159', 'Staten Island': '3827'}, '1800': {'Bronx': '1781', 'Brooklyn': '4549', 'Manhattan': '33131', 'Queens': '6159', 'Staten Island': '3827'},
buran write May-21-2021, 04:50 AM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
There is nums in this code which you modify and return and I have no idea what it is. Not to mention that there are no clues how your function inputs look like and what is the expected result.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
The following code will recursively display the contents of a dictionary nested or not.
    def display_dict(dictname, level=0):
        indent = " " * (4 * level)
        for key, value in dictname.items():
            if isinstance(value, dict):
                print(f'\n{indent}{key}')
                level += 1
                display_dict(value, level)
            else:
                print(f'{indent}{key}: {value}')
            if level > 0:
                level -= 1
level is used internally to control the node level.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020