HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModerate

Merging two lists from dictionary. How to do this in a better way?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thishowmergingwaybettertwolistsdictionaryfrom

Problem

I have the following code:

print o
# {'actor_name': [u'Keanu Reeves', u'Laurence Fishburne', u'Carrie-Anne Moss', u'Hugo Weaving', u'Glor
# ia Foster', u'Joe Pantoliano', u'Marcus Chong', u'Julian Arahanga', u'Belinda McClory', u'Matt Doran
# '], 'played': [u'Neo (Thomas Anderson)', u'Morfeusz', u'Trinity', u'Agent Smith', u'Wyrocznia', u'Cy
# pher', u'Tank', u'Apoc', u'Switch', u'Mouse']}
li = list(o.itervalues())
for index, value in enumerate(li[0]):
    print [value, li[1][index]]
# [u'Keanu Reeves', u'Neo (Thomas Anderson)']
# [u'Laurence Fishburne', u'Morfeusz']
# [u'Carrie-Anne Moss', u'Trinity']
# [u'Hugo Weaving', u'Agent Smith']
# [u'Gloria Foster', u'Wyrocznia']
# [u'Joe Pantoliano', u'Cypher']
# [u'Marcus Chong', u'Tank']
# [u'Julian Arahanga', u'Apoc']
# [u'Belinda McClory', u'Switch']
# [u'Matt Doran', u'Mouse']


I'm curious how I could write this thing in a more Pythonic way without losing its readability.

Solution

You're looking for zip().

print zip(o['actor_name'], o['played'])


or to make it look like your output

for entry in zip(o['actor_name'], o['played']):
    print entry

Code Snippets

print zip(o['actor_name'], o['played'])
for entry in zip(o['actor_name'], o['played']):
    print entry

Context

StackExchange Code Review Q#1260, answer score: 10

Revisions (0)

No revisions yet.