Py学习  »  Python

在Python中,可以将列表中的元素添加到字典的值中吗?

user04012001 • 3 年前 • 1373 次点击  

我试图将列表的元素添加到字典的值中。

我创建了一个列表,其中包含一个文件中的元素,如下所示:

list_of_lists = [[966], [1513, 2410], [2964, 1520, 604]....] 

我正试图将此列表添加到我制作的字典中,使其看起来像这样:

{'Youngstown': ['OH', 4110, 8065, 115436], 'Yankton': ['SD', 4288, 9739, 
12011], 'Yakima': ['WA', 4660, 12051, 49826]....]

我尝试了以下代码:

 x = 1
 for x in d2.values():
     d2.append(list_of_list)
 print(d2)

我甚至不确定这是否是可能的,但我正在努力让字典:

{'Youngstown': ['OH', 4110, 8065, 115436], 'Yankton': ['SD', 4288, 9739, 
12011, [966]], 'Yakima': ['WA', 4660, 12051, 49826, [1513, 2410]]....]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133277
 
1373 次点击  
文章 [ 3 ]  |  最新文章 3 年前
Pranav Hosangadi
Reply   •   1 楼
Pranav Hosangadi    3 年前

是的 x = 1 ,然后你马上 for x in d2.values() .这会覆盖 x 每一个元素 d2.values() .如果你想从第二项开始 d2。价值观() ,需要创建迭代器并跳过第一个值:

d2_iter = iter(d2.values())
next(d2_iter) # Consume one element
for item in d2_iter: # Iterate over the remaining iterator
    # Do what you want here.

另一个问题是附加 整个列表 每一个价值 在里面 d2 .不要那样做。改用 zip() 遍历列表列表和中的值 d2 同时

d2_iter = iter(d2.values())
next(d2_iter) # Consume one element
for item_from_dict, item_to_append in zip(d2_iter, list_of_lists): 
    item_from_dict.append(item_to_append)

这就给你留下了:

{'Youngstown': ['OH', 4110, 8065, 115436],
 'Yankton': ['SD', 4288, 9739, 12011, [966]],
 'Yakima': ['WA', 4660, 12051, 49826, [1513, 2410]]}

请注意,像这样的附加只起作用,因为列表是可变的。如果有一个不可变的类型,比如元组,作为 d2 ,则必须创建一个新元组并将其分配给键:

d3 = {'Youngstown': ('OH', 4110, 8065, 115436), 'Yankton': ('SD', 4288, 9739, 12011), 'Yakima': ('WA', 4660, 12051, 49826)}

d3_iter = iter(d2.keys())
next(d3_iter) # Consume one element

for key_from_dict, item_to_append in zip(d3_iter, list_of_lists): 
    new_item = d3[key_from_dict] + (item_to_append,) # Create a new item
    d3[key_from_dict] = new_item

你会得到

{'Youngstown': ('OH', 4110, 8065, 115436),
 'Yankton': ('SD', 4288, 9739, 12011, [966]),
 'Yakima': ('WA', 4660, 12051, 49826, [1513, 2410])}
BrokenBenchmark
Reply   •   2 楼
BrokenBenchmark    3 年前

你可以用 itertools.islice() 跳过第一个元素,然后使用 zip() 要将每个列表值与要附加的列表配对,请执行以下操作:

from itertools import islice
for lst_value, lst_to_append in zip(islice(d2.values(), 1, None), list_of_lists):
    lst_value.append(lst_to_append)
    
print(d2)

这将产生:

{
 'Youngstown': ['OH', 4110, 8065, 115436],
 'Yankton': ['SD', 4288, 9739, 12011, [966]],
 'Yakima': ['WA', 4660, 12051, 49826, [1513, 2410]]
}
Sharim Iqbal
Reply   •   3 楼
Sharim Iqbal    3 年前

我知道有更多的方法可以做到这一点,但我认为这是更具可读性和可理解性的代码。

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_)