简体   繁体   English

将dict转换为列表

[英]Converting a dict into a list

I have 我有

{key1:value1, key2:value2, etc}

I want it to become: 我希望它成为:

[key1,value1,key2,value2] , if certain keys match certain criteria.

How can i do it as pythonically as possible? 我怎么能尽可能地蟒蛇化呢?

Thanks! 谢谢!

This should do the trick: 这应该做的伎俩:

[y for x in dict.items() for y in x]

For example: 例如:

dict = {'one': 1, 'two': 2}

print([y for x in dict.items() for y in x])

This will print: 这将打印:

['two', 2, 'one', 1]

given a dict , this will combine all items to a tuple 给定一个dict ,这将把所有项目组合成一个元组

sum(dict.items(),())

if you want a list rather than a tuple 如果你想要一个列表而不是一个元组

list(sum(dict.items(),()))

for example 例如

dict = {"We": "Love", "Your" : "Dict"}
x = list(sum(dict.items(),()))

x is then 然后是x

['We', 'Love', 'Your', 'Dict']

This code should solve your problem: 此代码应该可以解决您的问题:

myList = []
for tup in myDict.iteritems():
    myList.extend(tup)

>>> myList
[1, 1, 2, 2, 3, 3]

The most efficient (not necessarily most readable or Python is) 效率最高(不一定是最具可读性或Python)

from itertools import chain

d = { 3: 2, 7: 9, 4: 5 } # etc...
mylist = list(chain.from_iterable(d.iteritems()))

Apart from materialising the lists, everything is kept as iterators. 除了实现列表之外,所有内容都保留为迭代器。

Another entry/answer: 另一个条目/答案:

import itertools

dict = {'one': 1, 'two': 2}

bl = [[k, v] for k, v in dict.items()]
list(itertools.chain(*bl))

yields 产量

['two', 2, 'one', 1]
>>> a = {"lol": 1 }
>>> l = []
>>> for k in a.keys():
...     l.append( k )
...     l.append( a[k] )
... 
>>> l
['lol', 1]

If speed matters, use extend to add the key, value pairs to an empty list: 如果速度很重要,请使用extend将键值对添加到空列表中:

l=[]
for t in sorted(d.items()):
    return l.extend(t)


>>> d={'key1':'val1','key2':'val2'}
>>> l=[]
>>> for t in sorted(d.items()):
...    l.extend(t)
... 
>>> l
['key1', 'val1', 'key2', 'val2']

Not only faster, this form is easier to add logic to each key, value pair. 不仅更快,这种形式更容易为每个键,值对添加逻辑。

Speed comparison: 速度比较:

d={'key1':'val1','key2':'val2'}

def f1():
    l=[]
    for t in d.items():
        return l.extend(t)

def f2():
    return [y for x in d.items() for y in x]

cmpthese.cmpthese([f1,f2])

Prints: 打印:

    rate/sec    f2     f1
f2   908,348    -- -33.1%
f1 1,358,105 49.5%     --

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

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