-1

I have a list of strings:

list = ['FL9000', 'OV255', 'MK0029']. I want to create a dictionary by taking the first two characters from each string element for the key, and append the element itself for a value.

My result should be something like:

dict = {'FL': 'FL9000', 'OV': 'OV255'} and so on.

  • 1
    There are a couple hundreds post in [pyhton] how to slice strings or lists as well as how to create dicts. What did you try to do to solve that? why did all those posts not help you? – Patrick Artner Apr 25 '20 at 21:50
  • Dupe: [how-to-split-a-string-within-a-list-to-create-key-value-pairs-in-python](https://stackoverflow.com/questions/12739911/how-to-split-a-string-within-a-list-to-create-key-value-pairs-in-python) - instead of splitting -use string slicing – Patrick Artner Apr 25 '20 at 21:51
  • Think about it logically. You have a list of elements that you can iterate over. For each element, you can split the string (since you know the first two characters are your key). You can add the first half and the second half to a dictionary accordingly. – Sri Apr 25 '20 at 21:51
  • Yes, my logic is very similar to yours. Implementing the code itself is something that i can't do or i just handle it. Please don't be mad at me about my question. I read at least 40 pages before deciding to write my question here. – Denis Dragnev Apr 25 '20 at 21:54

2 Answers2

0

you can do something like that

l = ['FL9000', 'OV255', 'MK0029']
d = {}

for i in l: 
   d[i[0:2]] = i


d 
Out[14]: {'FL': 'FL9000', 'OV': 'OV255', 'MK': 'MK0029'}
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Beny Gj
  • 607
  • 4
  • 16
0

You can use :

l = ['FL9000', 'OV255', 'MK0029']
d = {x[0:2]: x for x in l}
# {'FL': 'FL9000', 'OV': 'OV255', 'MK': 'MK0029'}

Notes:

  • Demo
  • You shouldn't use built-in function names as variables (dict, list)
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • Thank you, it is worked. I have a question - my list includes 2000+ strings, but when implementing the code above the result always returns only 4 key: value pairs. Why is that? – Denis Dragnev Apr 25 '20 at 22:37
  • you're welcome, If my answer helped you, please consider accepting it as the correct answer by clicking on the check-mark ✅, thanks! Here's this code working with more items https://trinket.io/python3/84cd6f137c - You may consider using the code on my answer, to open another question and post the url here so I can help you. – Pedro Lobito Apr 25 '20 at 22:40