我正在运行此代码,以将三个列表组合成一个字典,其中第一个列表为键。
list_dict = {x: (y, z) for x, y, z in zip_longest(order_instance, final_mem, final_disk)}
pprint(list_dict)
返回此...
{'instanceIndex:0': ('212590592', '192389120'),
'instanceIndex:1': ('5971968', '13963264'),
'instanceIndex:2': ('93331456', '216592384')}
我希望能够格式化此字典以显示y和z值的键,从而使其更易于输入到SQL数据库中。像这样的东西。
{'instanceIndex:0': ((Memory: '212590592'),
(Disk: '192389120')),
'instanceIndex:1': ((Memory: '5971968'),
(Disk: '13963264')),
'instanceIndex:2': ((Memory: '93331456'),
(Disk: '216592384'))}
答案 0 :(得分:2)
您可以直接修改dict-comprehension以匹配您选择存储值的任何格式。就您而言,键值格式类似于dict
的键值格式,因此请使用它。
list_dict = {x: {'Memory':y, 'Disk':z} for x, y, z in zip_longest(order_instance, final_mem, final_disk)}
# ^^^^^^^^^^ ^^^^^^^^ ^
答案 1 :(得分:0)
您可以使用collections.namedtuples
将数据存储为命名元组:
class EventTest(APITestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user(email='test@gmail.com',
password='password')
def test_post_create_event(self):
factory = factories.EventFactory.build()
serializer = serializers.EventSerializer(factory)
# IMPORTANT: Calling 'serializer.data' is the exact place the error occurs!
# This error does not occur when I remove the ManyToManyField
res = self.post_api_call('/event/', serializer.data)
输出:
from itertools import zip_longest
from collections import namedtuple
from pprint import pprint
inst = ["i1","i2","i3"]
memo = ["1","2","3"]
disk = ["d1","d2","d3"]
Data = namedtuple("Data", ["Memory","Disk"])
k = {x: Data(m,d) for x, m, d in zip_longest(inst,memo,disk)}
pprint(k)
您可以按索引或按名称访问命名元组:
{'i1': Data(Memory='1', Disk='d1'),
'i2': Data(Memory='2', Disk='d2'),
'i3': Data(Memory='3', Disk='d3')}