Luis Henrique
Luis Henrique

Reputation: 771

How to replace a string inside a python dictionary using regex

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'}

Upvotes: 1

Views: 94

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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'}}

Upvotes: 1

Related Questions