我有一个字典形式的列表,如下所示:
[{0: [6]},
{0: [1, 4, 5, 6]},
{0: [3]},
{2: [1, 13, 15]},
{2: [8, 19]},
{2: [8]},
{2: [1, 23]},
{2: [8, 26]},
{2: [23]},
{2: [23]},
{2: [23, 34]},
{2: [39]},
{2: [23, 34, 1]},
{2: [1, 42]},
{2: [23, 34]},
{2: [24]},
{2: [15, 8]},
{3: [5, 6, 8, 9]},
{3: [0]},
{3: [1]},
{3: [5, 6, 13, 17, 18]},
{3: [12]},
{3: [2, 6, 9, 13, 15, 16]},
{3: [4, 5, 6, 17, 20, 21, 22]},
{3: [5, 12, 17, 20, 21, 26, 27]},
{3: [2, 8, 9, 22, 26, 28]},
{3: [4, 5, 6, 20, 21, 8, 1, 13, 32, 33]},
{3: [16, 13]},
{3: [9, 17, 20, 21, 27, 28, 32, 35, 36]},
{3: [6, 9, 16, 8, 37, 38]},
{3: [7, 9, 26, 27, 28, 29]},
{3: [9, 22, 1, 34]},
{3: [15, 25]},
{3: [29, 1]},
{3: [14, 20, 40]},
{3: [14, 13, 41]},
{3: [5, 32, 35, 36, 37, 38]},
{3: [6, 21, 42]}]
继续这样做一段时间。第一个数字非常重要。 现在我想找到值'0','2'和'3',看看哪些值与此相关。
我最终想要的是查找不同的值并保存列表中连接的所有值。
对于0:
0: [6,1, 4, 5, 6,3]
我真的不知道该怎么做。
答案 0 :(得分:2)
使用dict.setdefault()函数的解决方案(适用于所有值):
d = {}
for i in l:
k = list(i.keys())[0]
d.setdefault(k, [])
d[k] = d[k] + i[k]
print(d)
输出:
{0: [6, 1, 4, 5, 6, 3], 2: [1, 13, 15, 8, 19, 8, 1, 23, 8, 26, 23, 23, 23, 34, 39, 23, 34, 1, 1, 42, 23, 34, 24, 15, 8], 3: [5, 6, 8, 9, 0, 1, 5, 6, 13, 17, 18, 12, 2, 6, 9, 13, 15, 16, 4, 5, 6, 17, 20, 21, 22, 5, 12, 17, 20, 21, 26, 27, 2, 8, 9, 22, 26, 28, 4, 5, 6, 20, 21, 8, 1, 13, 32, 33, 16, 13, 9, 17, 20, 21, 27, 28, 32, 35, 36, 6, 9, 16, 8, 37, 38, 7, 9, 26, 27, 28, 29, 9, 22, 1, 34, 15, 25, 29, 1, 14, 20, 40, 14, 13, 41, 5, 32, 35, 36, 37, 38, 6, 21, 42]}
答案 1 :(得分:1)
您有一个相当奇怪的数据结构,但在编写时,可以使用以下代码对其进行修改:
list_of_dicts = [...]
output = dict()
for entry in list_of_dicts:
for key in entry:
if output.has_key(key):
output[key].append(entry[key])
else:
output[key] = entry[key]
请注意,此代码不会假设列表中的每个dict只有一个键,因为在一般情况下,每个dict可能包含多个条目。此外,代码不假设每个列表元素都是唯一的,在这种情况下,集合可能更合适。
答案 2 :(得分:0)
为什么不能像这样存储它们?
{
0 : [
[6],
[1,4,5,6]
...],
1 : ...
}
答案 3 :(得分:0)
那些数据的格式有点奇怪,但这可能会有用。我建议将这些数据放入比这更好的结构中。
def get_values(data, key=0):
out = []
for item in data:
if item.get(key):
out.extend(item[key])
return out
答案 4 :(得分:0)
这是一个很好的功能:
from itertools import chain
def find(index):
return list(chain.from_iterable([i[index] for i in d if i.keys()==[index]]))
其中给出了以下输出:
>>> find(0)
[6, 1, 4, 5, 6, 3]
>>> find(2)
[1, 13, 15, 8, 19, 8, 1, 23, 8, 26, 23, 23, 23, 34, 39, 23, 34, 1, 1, 42, 23, 34, 24, 15, 8]
>>>
答案 5 :(得分:0)
以下是您问题的简单逻辑代码:希望您能在此之后找到自己的出路;将在python(3)中完美地工作
f = [{0: [6]},
{0: [1, 4, 5, 6]},
{0: [3]},
{2: [1, 13, 15]},
{2: [8, 19]},
{2: [8]},
{2: [1, 23]},
{2: [8, 26]},
{2: [23]},
{2: [23]},
{2: [23, 34]},
{2: [39]},
{2: [23, 34, 1]},
{2: [1, 42]},
{2: [23, 34]},
{2: [24]},
{2: [15, 8]},
{3: [5, 6, 8, 9]},
{3: [0]},
{3: [1]},
{3: [5, 6, 13, 17, 18]},
{3: [12]},
{3: [2, 6, 9, 13, 15, 16]}]
c = int (input("Enter the number that you want to look for "))
z = []
for x in f:
for keys , values in x.items():
if keys==c :
z = z + values
print (z)
答案 6 :(得分:0)
d = {}
for i in l:
k,v = list(i.items())[0]
d.setdefault(k, []).extend(v)
print(d)