[英]Sync keys from a dictionary to multiple values in a list
i have a dict of list in following format, 我有以下格式的列表字典,
mydict =
{ a: [1, 2],
b: [2, 2],
c: [1, 0],
d: [1, 1]
}
and another list with just two elements, 另一个只有两个元素的列表,
mylist =
[x, y]
I read the values from mydict
like this 我像这样从
mydict
读取值
for key, values in mydict.items():
print key, values
this prints, 这印,
a [1, 2]
b [2, 2]
c [1, 0]
d [1, 1]
but i want the following output, 但我想要以下输出,
x : [1, 2, 1, 1]
y : [2, 2, 0, 1]
which means, the first column of mydict
and first value of mylist
makes a dictionary. 这意味着,
mydict
的第一列和mylist
第一个值构成一个字典。
so i modified loop like this, 所以我修改了这样的循环
for key, values in mydict.items():
newdict = {mylist[0]: mydict[0],
mylist[1]: mydict[1]
}
which gives me the desired output, 这给了我想要的输出,
x : [1, 2, 1, 1]
y : [2, 2, 0, 1]
but the problem is if the length of mylist
and mydict
increases then it won't work, and I need to manually add a new line, 但是问题是,如果
mylist
和mydict
的长度增加了,那么它将不起作用,并且我需要手动添加新行,
mylist[2]: mydict[2]
How can I make sure that keys are assigned automatically without add a new line, everytime new value in mylist
is added? 每当
mylist
中添加新值时,如何确保自动分配键而无需添加新行?
PS: lenth of list value in mydict
will always be equal to length of mylist
. PS:
mydict
中列表值的总长度将始终等于mylist
长度。
Edit: 编辑:
my output should also preserve value of keys from mydict
, 我的输出还应该保留
mydict
,
x : [1, 2, 1, 1]
y : [2, 2, 0, 1]
keys: a, b, c, d
thank you 谢谢
EDIT: 编辑:
0 1
0 a [1,2],
1 b [2,2],
2 c [1,0],
3 d [1,1]
You can use zip
2 您可以使用
zip
2
dict(zip(['x', 'y'], zip(*dct.values())))
# Result
{'x': (1, 2, 1, 1), 'y': (2, 2, 0, 1)}
This uses the zip
transpose: 这使用
zip
转置:
>>> list(zip(*dct.values()))
[(1, 2, 1, 1), (2, 2, 0, 1)]
If you want to keep your keys: 如果要保留密钥:
dict(zip(['key', 'x', 'y'], zip(*[(i, *j) for i, j in dct.items()])))
# Result
{'key': ('a', 'b', 'c', 'd'), 'x': (1, 2, 1, 1), 'y': (2, 2, 0, 1)}
If you are working with big data, you can use pandas
如果您正在使用大数据,则可以使用
pandas
import pandas as pd
mydict = { 'a': [1, 2],
'b': [2, 2],
'c': [1, 0],
'd': [1, 1]}
df = pd.DataFrame(mydict)
0 1
a 1 2
b 2 2
c 1 0
d 1 1
Then you can get, eg 然后你可以得到,例如
>>> df.columns = ['x', 'y'] # where ['x', 'y'] is your obj my_list
>>> df.to_dict('list')
{'x': [1, 2, 1, 1], 'y': [2, 2, 0, 1]}
To keep the keys 保持钥匙
>>> d = df.to_dict('list')
>>> d.update({'keys':df.index.tolist()})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.