简体   繁体   中英

Iterate over list using for loop

code:

d = ["my", "name", "is", "abc"]
a  = {x: x*2 for x in d}
print a

output:

{'is': 'isis', 'abc': 'abcabc', 'my': 'mymy', 'name': 'namename'}

the output was not in the order of "d" list.

I also tried this:

a = collections.Ordered({x: x*2 for x in d})

but couldn't got expected result.

How can i generate a dictionary with elements ordered same as "d" list ?

This works:

OrderedDict([(x, x*2) for x in d])

Output:

OrderedDict([('my', 'mymy'), ('name', 'namename'), ('is', 'isis'), ('abc', 'abcabc')])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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