0

In python, trying to convert the key-value pair from integer to string.

Input:

data = [
    {'code': 123456, 'value': 32},
    {'code': 987654, 'value': 12}
]

Expected Output

data = [
    {'code': '123456', 'value': 32},
    {'code': '987654', 'value': 12}
]

Trying for code-value.

2
  • what do you mean by "pad the key-value pair" ? Only difference I see is that you type-casted the values of 'code' from int to str. Is that what you mean? Commented Feb 4, 2021 at 20:20
  • Yes, You are right @Anonymous Commented Feb 4, 2021 at 20:21

2 Answers 2

2
for row in data:
    row['code'] = str(row['code'])
Sign up to request clarification or add additional context in comments.

Comments

1

Here's a dictionary comprehension inside a list comprehension to achieve this:

data = [
    {'code': 123456, 'value': 32},
    {'code': 987654, 'value': 12}
]

new_data = [{k: str(v) if k == 'code' else v for k, v in d.items()} for d in data]

where new_data will hold the data in your desired format as:

[{'code': '123456', 'value': 32}, {'code': '987654', 'value': 12}]

Inside the dictionary comprehension I am checking whether the key is 'code', and type-casting the value to str in case of a match.

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.