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.
If you are getting an object that has no attribute error then the reason behind it is because your indentation is goofed, and you've mixed tabs and spaces. Run the script with python -tt to verify.
Conclusion # The Python "AttributeError: 'list' object has no attribute 'replace'" occurs when we call the replace() method on a list instead of a string. To solve the error, call replace() on a string, e.g. by accessing the list at a specific index or by iterating over the list.
It's simply because there is no attribute with the name you called, for that Object. This means that you got the error when the "module" does not contain the method you are calling.
Solution for AttributeError Errors and exceptions in Python can be handled using exception handling i.e. by using try and except in Python. Example: Consider the above class example, we want to do something else rather than printing the traceback Whenever an AttributeError is raised.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With