-3

I have list:

['Location: NY',
 'price: 11103 USD', 
 'Year: 2018', 
 'Model: Golf VII',
'Security',
'Airbag']

how do I turn it into dictionary? I'm using different type of list than what is described in problem here. Also some list elements are empty, I need to omit them in final dictionary.

Hrvoje
  • 13,566
  • 7
  • 90
  • 104
  • Where is your [mre],where is your problem, what did you try? – Patrick Artner Oct 11 '19 at 11:52
  • Suppose, you have a list of pairs, e.g. `[('Location', 'NY'), ...]`. Do you know how to get this list and how to get from there to a dict? – bereal Oct 11 '19 at 11:56
  • Possible duplicate of [Convert a list to a dictionary in Python](https://stackoverflow.com/questions/4576115/convert-a-list-to-a-dictionary-in-python) – mulaixi Oct 11 '19 at 11:57
  • It's not duplicate, check that already and tried all of that as well.. – Hrvoje Oct 11 '19 at 11:58

7 Answers7

3

If your pattern always like you depict, you can split(': ') your items

my_list = ['Location: NY', 'price: 11103 USD', 'Year: 2018', 'Model: Golf VII']
my_dict = { i.split(': ')[0] : i.split(': ')[1] for i in my_list }

ADDITION FOR THE EMPTY VALUES:

You can also extract your logic into a function and make some other controls (trimming, null values etc), and still use dictionary comprehension as follows:

def str_to_keyval(inp, separator=':'):
  # to list
  li = inp.split(separator) if (separator in inp) else [inp, '']
  # strip elements
  return [i.strip() for i in li]

my_list = [
  'Location: NY',
  'price: 11103 USD',
  'Year: 2018',
  'Model: Golf VII',
  'Security',
  'Airbag'
]

my_dict = { str_to_keyval(i)[0] : str_to_keyval(i)[1] for i in my_list }

You can change the presentation of null values (ignore their keys, or denote with an empty string etc.) through editing the first line of str_to_keyval function in the example. As it is, it gives empty string as missing values.

vahdet
  • 6,357
  • 9
  • 51
  • 106
  • what if I have empty elements in list...which is reason why all of this is not working initially – Hrvoje Oct 11 '19 at 12:24
  • So, how *empty* are they? Still have keys? Totally empty strings? – vahdet Oct 11 '19 at 12:53
  • I've edited my question. Keys are there but values are missing. Separator is missing as well for those empty elements. – Hrvoje Oct 11 '19 at 13:00
2

You can use do a dict comperhension for this application,

My solution is similar to that of @vahdet's answer, but this solution will take care of multiple spaces that may occur in key or value.

l = ['Location: NY',
 'price: 11103 USD', 
 'Year: 2018', 
 'Model: Golf VII']

dict( (x.split(':')[0].strip(),  x.split(':')[1].strip()) for x in l )

You can make use of this same dict comprehension to handle invalid items in the list by checking whether : exists in the list or not like this and adding the key-value only if the item is valid,

l = ['Location: NY',
     'price: 11103 USD',
     'Year: 2018',
     'Model: Golf VII',
     'Security',
     'Airbag']

print(dict((x.split(':')[0].strip(), x.split(':')[1].strip()) for x in l if ':' in x))
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
1

Ok, so the first thing you'll need to do is loop over every item in the list. This is pretty easy using a for loop

for item in lst:
    # do stuff with the item

After that, you'll need to separate the item into a key and a value. The keys and values are already separated by a colon and a space, so I would just split the string using that.

for item in lst:
    split_item = item.split(": ")
    key = split_item[0]
    value = split_item[1]
    # then you need to add the key and item to the dictionary

Adding the value is pretty simple. Just define the new value:

dictionary = {} # just to initialize the dictionary, if you already initialized it, don't do this
for item in lst:
    split_item = item.split(": ")
    key = split_item[0]
    value = split_item[1]
    dictionary[key] = value

That's it

Botahamec
  • 263
  • 3
  • 8
1

You can use the split function to get the parts of each string to create your dictionary reference:

arr = ['Location: NY', 'price: 11103 USD', 'Year: 2018', 'Model: Golf VII']
dict = {}

for i in range(0, len(arr)):
    key, value = arr[i].split(": ")
    dict[key] = value

print(dict)
Omari Celestine
  • 1,405
  • 1
  • 11
  • 21
1

With this list:

mylist = ['Location: NY',
 'price: 11103 USD', 
 'Year: 2018', 
 'Model: Golf VII']

Try following code:

mydict = {}
for l in mylist: 
    a,b = l.split(': ')
    mydict[a] = b
print(mydict)

Output:

{'Year': '2018', 'Model': 'Golf VII', 'price': '11103 USD', 'Location': 'NY'}
rnso
  • 23,686
  • 25
  • 112
  • 234
1

You can use a simple comprehension with dict:

my_list = ['Location: NY', 'price: 11103 USD', 'Year: 2018', 'Model: Golf VII']
result = dict(i.split(': ') for i in my_list)

Output:

{'Location': 'NY', 'price': '11103 USD', 'Year': '2018', 'Model': 'Golf VII'}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
-3
a=['Location: NY',
 'price: 11103 USD',
 'Year: 2018',
 'Model: Golf VII']

   b=[]

   x={}

   for i in range(len(a)):

       b.append(a[i].split(':'))


   for i in range(len(b)):

       for j in range(len(b[i])):

          x[b[i][0]]=b[i][1]

   print(x)
Joe
  • 8,073
  • 1
  • 52
  • 58
  • Code-only answers are generally frowned upon on this site. Could you please edit your answer to include some comments or explanation of your code? Explanations should answer questions like: What does it do? How does it do it? Where does it go? How does it solve OP's problem? See: [How to anwser](https://stackoverflow.com/help/how-to-answer). Thanks! – Eduardo Baitello Oct 11 '19 at 14:38