Вопрос

I know this is a basic question, but I'm new to python and can't figure out how to solve it.

I have a list like the next example:

entities = ["#1= IFCORGANIZATION($,'Autodesk Revit 2014 (ENU)',$,$,$)";, "#5= IFCAPPLICATION(#1,'2014','Autodesk Revit 2014 (ENU)','Revit');"]

My problem is how to add the information from the list "entities" to a dictionary in the following format:

dic = {'#1= IFCORGANIZATION' : ['$','Autodesk Revit 2014 (ENU)','$','$','$'], '#5= IFCAPPLICATION' : ['#1','2014','Autodesk Revit 2014 (ENU)','Revit']

I tried to do this using "find" but I'm getting the following error: 'list' object has no attribute 'find',

and I don't know how to do this without find method.

Это было полезно?

Решение 2

You could use str.split to deal with strings. First split each element string with '(', with maxsplit being 1:

In [48]: dic=dict(e[:-1].split('(', 1) for e in entities) #using [:-1] to filter out ')'
    ...: print dic
    ...: 
{'#5= IFCAPPLICATION': "#1,'2014','Autodesk Revit 2014 (ENU)','Revit')", '#1= IFCORGANIZATION': "$,'Autodesk Revit 2014 (ENU)',$,$,$)"}

then split each value in the dict with ',':

In [55]: dic={k: dic[k][:-1].split(',') for k in dic}
    ...: print dic
{'#5= IFCAPPLICATION': ['#1', "'2014'", "'Autodesk Revit 2014 (ENU)'", "'Revit'"], '#1= IFCORGANIZATION': ['$', "'Autodesk Revit 2014 (ENU)'", '$', '$', '$']}

Note that the key-value pairs in a dict is unordered, as you may see '#1= IFCORGANIZATION' is not showing in the first place.

Другие советы

If you want to know if a value is in a list you can use in, like this:

>>> my_list = ["one", "two", "three"]
>>> "two" in my_list
True
>>> 

If you need to get the position of the value in the list you must use index:

>>> my_list.index("two")
1
>>> 

Note that the first element of the list has the 0 index.

Here you go:

>>> import re
>>> import ast
>>> entities = ["#1= IFCORGANIZATION('$','Autodesk Revit 2014 (ENU)','$','$','$');", "#5= IFCAPPLICATION('#1','2014','Autodesk Revit 2014 (ENU)','Revit');"]
>>> entities = [a.strip(';') for a in entities]
>>> pattern = re.compile(r'\((.*)\)')
>>> dic = {}
>>> for a in entities:
...     s = re.search(pattern, a)
...     dic[a[:a.index(s.group(0))]] = list(ast.literal_eval(s.group(0)))
>>> dic
{'#5= IFCAPPLICATION': ['#1', '2014', 'Autodesk Revit 2014 (ENU)', 'Revit'], '#1= IFCORGANIZATION': ['$', 'Autodesk Revit 2014 (ENU)', '$', '$', '$']}

This regex r'\((.*)\)' looks for elements in ( and ) and converts them to a list. It makes the sub string appearing before the brackets as the key and the list as the value.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top