Search code examples
pythondictionarydefaultdict

Defaultdict - assign strings to key value in loop


I am struggling to understand why the string values I am trying to loop through and assign to dictionary key-value pairs in a default dictionary are not properly working.

The desired outcome here is to loop through the string values in each of the two lists, and return a dictionary that has websites for keys and team names for values. However, neither append nor the equal sign work. In addition, I am not sure why the defaultdict returns of the form defaultdict(None, {}) (or defaultdict(list, {}) if i initiate it as a list). Is there a way to assert that both the keys and values of this dict will be strings?

Thank you for your help.

teams=['yankees','redsox','giants']
websites=['xasfsgrwg.cc','redsox.com','giants.org']

from collections import defaultdict 
baseballdict=defaultdict() #defaultdict(None, {})
#baseballdict=defaultdict(list)

for i in range(len(websites)):
    baseballdict[websites[i]]=baseballdict[teams[i]] #does not work 
    baseballdict[websites[i]].append(baseballdict[teams[i]]) # does not work

Solution

  • You are doing wrong assigning and appending in last lines of your code.

    This is a fix for your code.

    teams=['yankees','redsox','giants']
    websites=['xasfsgrwg.cc','redsox.com','giants.org']
    
    baseballdict={}
    
    for i in range(len(websites)):
        baseballdict[websites[i]]=teams[i] 
    
    print(baseballdict)# prints dictionary