简体   繁体   English

将字典转换为元组

[英]Convert dictionary into tuples

I have the following dictionary: 我有以下字典:

myDict = {0:{'value1':25,'value2':2500},1:{'value1':35,'value2':1000}}

Which I would like converted into tuples looking like this: 我希望将其转换为如下所示的元组:

((25,2500),(35,1000))

By using the below code create a one-dimensional tuple for the 0 key. 通过使用下面的代码为0键创建一维元组。 However I would like to create a multi-dimensional tuple. 但是我想创建一个多维元组。

tup = tuple(myDict[0].values())

just do it by simple loop: 通过简单的循环来做到这一点:

tuple(tuple(x.values()) for x in myDict.values())

if you need to sort result by dict key you can do it using sorted 如果你需要按dict键对结果进行排序,你可以使用sorted进行sorted

tuple(tuple(v.values()) for k, v in sorted(myDict.items()))

This will return the tuple s in order, 这将按顺序返回tuple

>>> myDict
{0: {'value2': 2500, 'value1': 25}, 1: {'value2': 1000, 'value1': 35}}
>>> tuple((v['value1'], v['value2']) for k,v in sorted(myDict.items()))
((25, 2500), (35, 1000))
#   # order based on keyfunc ?
>>> tuple((v['value1'], v['value2']) for k,v in sorted(myDict.items(), key=lambda x: x[1]['value1']))
((25, 2500), (35, 1000))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM