Reputation: 817
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
Upvotes: 0
Views: 2220
Reputation: 3988
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
Upvotes: 0
Reputation: 590
To create a defaultdict that has the type string as the key type, you should create like my_dict = defaultdict(str)
. And for having a dictionary that has the websites as keys and teams as values you should do:
for i in range(len(websites)):
baseballdict[websites[i]] = teams[i]
Upvotes: 0