Reputation: 23
I'm a starting programmer, and I can't figure out how to remove the brackets and the commas from the values I'm pulling out of a dictionary with lists. What did I miss?
From what I know, a for loop normally removes them, but doesn't do it now.
simplified code:
dict = {
'name1': ['python', 'c', 'java'],
'name2': ['c.'],
'name3': ['ruby', 'go'],
'name4': ['javascript', 'python'],
'name5': [],
}
for k, v in dict.items():
if len(v) == 1:
print(str(k).title() + "'s favorite language is " + str(v).title() + "\n")
elif len(v) > 1:
print(str(k).title() + "'s favorite languages are: \n" + str(v).title() + "\n")
elif len(v) < 1 :
print(str(k).title() + " does not have a favorite language")
Upvotes: 2
Views: 587
Reputation: 1882
While Daniel's answer is more elegant and complete, I want to address your question about why the 'for' function did not split the language names (remove "," and "]"). The first 'for' function in your code iterates through the dictionary. If you wanted to just use 'for' functions, you would need to reuse it again for each persons's entry to separate the languages. Like code sample below.
dict = {
'name1': ['python', 'c', 'java'],
'name2': ['c.'],
'name3': ['ruby', 'go'],
'name4': ['javascript', 'python'],
'name5': [],
}
for k, v in dict.items():
if len(v) == 1:
print(str(k).title() + "'s favorite language is " + str(v).title() + "\n")
elif len(v) > 1:
print(str(k).title() + "'s favorite languages are:")
for language in v:
print(language + ", ")
print("")
elif len(v) < 1 :
print(str(k).title() + " does not have a favorite language")
Upvotes: 1
Reputation: 61910
dict = {
'name1': ['python', 'c', 'java'],
'name2': ['c.'],
'name3': ['ruby', 'go'],
'name4': ['javascript', 'python'],
'name5': [],
}
for k, v in dict.items():
if len(v) == 1:
print(str(k).title() + "'s favorite language is " + ', '.join(map(str.title, v)) + "\n")
elif len(v) > 1:
print(str(k).title() + "'s favorite languages are: \n" + ', '.join(map(str.title, v)) + "\n")
elif len(v) < 1 :
print(str(k).title() + " does not have a favorite language")
Output
Name3's favorite languages are:
Ruby, Go
Name5 does not have a favorite language
Name2's favorite language is C.
Name4's favorite languages are:
Javascript, Python
Name1's favorite languages are:
Python, C, Java
The idea is to apply str.title
to each string in the list of values (using map) and then join those strings by comma and whitespace (', '
). Note that you can change the string of the join to fit your needs.
Upvotes: 3