I am trying to add the elements of a list of list to the values of a dictionary.
I have created a list with elements from a file that looks like this:
list_of_lists = [[966], [1513, 2410], [2964, 1520, 604]....]
I am trying to add this list to a dictionary that I have made to look like this:
{'Youngstown': ['OH', 4110, 8065, 115436], 'Yankton': ['SD', 4288, 9739,
12011], 'Yakima': ['WA', 4660, 12051, 49826]....]
I have tried the following code:
x = 1
for x in d2.values():
d2.append(list_of_list)
print(d2)
I am not even sure that this is something that is possible, but I am trying to get the dictionary to be:
{'Youngstown': ['OH', 4110, 8065, 115436], 'Yankton': ['SD', 4288, 9739,
12011, [966]], 'Yakima': ['WA', 4660, 12051, 49826, [1513, 2410]]....]
>Solution :
I know there are more ways to do that, But I think this is more readable and understandable code.
list_of_lists = [[966], [1513, 2410], [2964, 1520, 604]]
dict_ = {'Youngstown': ['OH', 4110, 8065, 115436], 'Yankton': ['SD', 4288, 9739,
12011], 'Yakima': ['WA', 4660, 12051, 49826]}
i = 0
# list(dict_.items())[1:] is the list of all keys and values except first one.
for key,value in list(dict_.items())[1:]:
dict_[key] = value+[list_of_lists[i]]
i+=1
print(dict_)