简体   繁体   中英

How do I convert a list of strings into dict where only a certain type at an unknown index can become the keys?

I have a list of strings that looks, like this:

myList = [
  "this 1 is my string",
  "a nice 2 string",
  "string is 3 so nice"
]

I'd like to convert this string into a dict that also looks, like this:

{
  "1": "this is my string",
  "2": "a nice string",
  "3": "string is so nice"
}

I don't know how to do this.

Only the integer can become the key but everything else must become the value, thank you.

If you multiple numbers in a line, it will take the first number as the key for the dict ,

>>> for line in myList:
...   match = re.search(r'\d+',line)
...   if match:
...     num = match.group()
...     newline = line.partition(num) # control over the partition
...     newline = newline[0].strip() + ' '.join(newline[2:])
...     d[num] = newline
... 
>>> 
>>> d
{'1': 'this is my string', '3': 'string is so nice', '2': 'a nice string'}
import re

myDict = {}

for element in myList:
    # Find number using regex.
    key = re.findall(r'\d+', element)[0]
    # Get index of number.
    index = element.index(key)
    # Create new string with index and trailing space removed.
    new_element = element[:index] + element[index + 2:]
    # Add to dict.
    myDict[key] = new_element

The simplest way to do this without installing any external dependencies is by using the findall method from the re module.

from re import findall

def list_to_dict(lst):
  result = {}
  for value in lst:
    match = findall(r"\d", value)
    if len(match) > 0:
      result[match[0]] = value.replace(match[0], "").replace("  ", " ")
  return result

If you wanted to, you could replace the 0 index with another index, although you should only do this if you are certain you know where the integer's index is.

Then using your list:

my_list = [
  "this 1 is my string",
  "a nice 2 string",
  "string is 3 so nice"
]

You'd call the function, like this:

print(list_to_dict(my_list))

Which should output this dict :

{'1': 'this is my string', '2': 'a nice string', '3': 'string is so nice'}

Good luck.

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