Annamarie
Annamarie

Reputation: 313

python parse string and turn into dictionary input

this is my list:

list1 = ('/a/b/c/Hello1/d/e','/a/b/c/Hello2/d/e','/a/b/c/Hello3/d/e')
list2 = []

for x in list1:
    y = x.split('/')[4]
    list2.append(y)

list2 = ['Hello1', 'Hello2', 'Hello3']

Now I want to create a dictionary where Hello[1-3] is my key and the corresponding string '/a/b/c/Hello[1-3]/d/e' is the value. How can I connect key and value in python. I am sure this is fairly easy, but I don't know.

Thank you.

Upvotes: 1

Views: 991

Answers (2)

dylrei
dylrei

Reputation: 1746

Assuming that you have the same number of elements in list1 and list2:

dict(zip(list2, list1))

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 118021

You can use a dict comprehension to achieve this.

>>> {s.split('/')[4] : s for s in list1}
{'Hello2': '/a/b/c/Hello2/d/e',
 'Hello3': '/a/b/c/Hello3/d/e',
 'Hello1': '/a/b/c/Hello1/d/e'}

Upvotes: 2

Related Questions