将字符串转换为dict并按升序排序

时间:2018-03-08 00:54:47

标签: python string python-3.x dictionary

{“timid”:”34567”, “version”:”1”,”binary_data”:”fsfdsfsdfasdfasdfsfasfdsa”,”seqNumber”:”101”}

{“timid”:”32567”, “version”:”1”,”binary_data”:”fsfsdfdsfdsfdsfsfsdfpipi”,”seqNumber”:”109”}

{“timid”:”36567”, “version”:”1”,”binary_data”:”fsfdsfsdfafsdfdsfsfasdfsfasfdsa”,”seqNumber”:”100”}

我有一个包含上述格式的字符串的文件,我想将字符串转换为字典并使用python3中的seq编号对记录进行排序。 我一直在尝试下面的方法,但没有成功。任何帮助深表感谢!提前致谢

import json
import ast
filename = 'u-data'

with open(filename) as f:
    string1 = f.read()
    # ast.literal_eval(string1)
    data = dict(string1.split(':') for x in string1.split(','))
    f.close()
    # string1 = string1[1:-2]
print(data)

2 个答案:

答案 0 :(得分:1)

我认为这应该有效:

data = ast.literal_eval(string1)

使用ast.literal_eval()时发生了什么?

修改

首先这样做:

string1 = string1.replace('“',"'").replace('”',"'")

你有一些双重报价搞砸了。然后运行:

data = ast.literal_eval(string1)

答案 1 :(得分:1)

这是一个解决方案。我使用pandas是为了方便,但这很容易适应非熊猫变体。

from io import StringIO
from ast import literal_eval
import pandas as pd

mystr = StringIO("""{'timid':'34567', 'version':'1','binary_data':'fsfdsfsdfasdfasdfsfasfdsa','seqNumber':'101'}
{'timid':'32567', 'version':'1','binary_data':'fsfsdfdsfdsfdsfsfsdfpipi','seqNumber':'109'}
{'timid':'36567', 'version':'1','binary_data':'fsfdsfsdfafsdfdsfsfasdfsfasfdsa','seqNumber':'100'}
""")

# read file
df = pd.read_csv(mystr, header=None, sep='|')

# create list of dictionaries
lst = df[0].map(literal_eval).tolist()

# sort list
res = sorted(lst, key=lambda x: int(x['seqNumber']))

# [{'binary_data': 'fsfdsfsdfafsdfdsfsfasdfsfasfdsa',
#   'seqNumber': '100',
#   'timid': '36567',
#   'version': '1'},
#  {'binary_data': 'fsfdsfsdfasdfasdfsfasfdsa',
#   'seqNumber': '101',
#   'timid': '34567',
#   'version': '1'},
#  {'binary_data': 'fsfsdfdsfdsfdsfsfsdfpipi',
#   'seqNumber': '109',
#   'timid': '32567',
#   'version': '1'}]