1

GOAL

How to replace a string inside a python dictionary using regex?

SCRIPT

db_result = cursor.fetchall() # databse

lds_data = {} # dictonary

regex = re.compile(r'^([^: \\]+)')
for lds_item in db_result:
    lds_data.update({re.findall(regex, lds_item[1]) : {'cust_code' : lds_item[0], 'osplatofrm' : lds_item[2]]}})

ERROR - OUTPUT

TypeError: unhashable type: 'list'

DB_RESULT

CODE_CLIENT  HOSTNAME     OSPLATFORM
    1       SRVDATA:23   WINSERVER

FINAL EXPECTED

{SRVDATA : {'CUST_CODE': 1, 'OSPLATFORM': 'WINSERVER'}
9
  • 2
    re.findall returns a list which can not be used as a dict key Commented Oct 11, 2019 at 14:40
  • 2
    re.findall(regex, lds_item[1]) returns a list, which you then try to set as a key in your dictionary. this fails as dict keys must be immutable objects (strings, ints, etc.) Commented Oct 11, 2019 at 14:40
  • How to fix? @RomanPerekhrest Commented Oct 11, 2019 at 14:41
  • How to fix? @Dan Commented Oct 11, 2019 at 14:42
  • @LuisV., post db_result and the final expected result. What is the goal to use a sequence as a dict key? Commented Oct 11, 2019 at 14:42

1 Answer 1

1

Simple approach:

# sample DB result (of one record)
db_result = [[1, 'SRVDATA:23', 'WINSERVER']]
lds_data = {}

for lds_item in db_result:
    k = lds_item[1][:lds_item[1].rfind(':')]   # extracting key
    lds_data.update({k: {'cust_code': lds_item[0], 'osplatofrm': lds_item[2]}})

print(lds_data)   # {'SRVDATA': {'cust_code': 1, 'osplatofrm': 'WINSERVER'}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.