简体   繁体   中英

Convert text file to a dictionary of key strings and value integers

i have a text file of numbers like so

text.file '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 i would like to convert this to an array like so:

myary= {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} but i want the keys to be a string and the values to be integer

i think i am able to get all of this as a string but that is not what i want i want it to be seprate

using ast.literal_eval

import ast
txt = "'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9"
print (ast.literal_eval('{' + txt + '}'))
#{'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

If you don't want to use literal_eval

str="'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9"
print({x[0].replace("'", ""):int(x[1]) for x in [y.split(': ') for y in [z for z in str.split(',')]] })
#{'2': 2, '7': 7, '8': 8, '4': 4, '1': 1, '9': 9, '3': 3, '6': 6, '5': 5}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM