Python将字符串解析为字典

2024-03-29 05:49:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字符串:

"[['Categories', [['180972'], ['180800'], ['16228'], ['32733'], ['32789'], ['32833'], ['325137'], ['32839'], ['25329'], ['42605'], ['428240849'], ['5101'], ['568'], ['570716'], ['57116'], ['57080545404'], ['57083134076']]], ['Tags', ['Stock', 'Color', 'Fam', 'Dress','Maxi']], ['Type', ['Luxary']], ['Vendor', ['AAA']]]"

我想把它解析为dict/json。 最好的方法是什么?你知道吗


Tags: 方法字符串jsontypestocktagsdictcolor
3条回答

尝试将其转换为dict:

data= "[['Categories', [['180972'], ['180800'], ['16228'], ['32733'], ['32789'], ['32833'], ['325137'], ['32839'], ['25329'], ['42605'], ['428240849'], ['5101'], ['568'], ['570716'], ['57116'], ['57080545404'], ['57083134076']]], ['Tags', ['Stock', 'Color', 'Fam', 'Dress','Maxi']], ['Type', ['Luxary']], ['Vendor', ['AAA']]]"

data = eval(data)

d={}
for i in data:
    d[i[0]] = [x for x, in i[1]] if isinstance(i[1][0], list) else i[1]

输出为:

{'Categories': 
  ['180972',
   '180800',
   '16228',
   '32733',
   '32789',
   '32833',
   '325137',
   '32839',
   '25329',
   '42605',
   '428240849',
   '5101',
   '568',
   '570716',
   '57116',
   '57080545404',
   '57083134076'],
 'Tags': ['Stock', 'Color', 'Fam', 'Dress', 'Maxi'],
 'Type': ['Luxary'],
 'Vendor': ['AAA']
}

这个怎么样

>>> import itertools
>>> import ast
>>> import pprint
>>> i = ast.literal_eval(s)
>>> d = {k[0]:list(itertools.chain(*k[1])) if isinstance(k[1][0], list) else list(k[1]) for k in i}
>>> pprint.pprint(d)
{'Categories': ['180972',
                '180800',
                '16228',
                '32733',
                '32789',
                '32833',
                '325137',
                '32839',
                '25329',
                '42605',
                '428240849',
                '5101',
                '568',
                '570716',
                '57116',
                '57080545404',
                '57083134076'],
 'Tags': ['Stock', 'Color', 'Fam', 'Dress', 'Maxi'],
 'Type': ['Luxary'],
 'Vendor': ['AAA']}

可以使用ast.literal_eval计算字符串并返回Python对象(如果语法正确)。Using this is safer than using ^{}。你知道吗

import ast

s = "[['Categories', [['180972'], ['180800'], ['16228'], ['32733'], ['32789'], ['32833'], ['325137'], ['32839'], ['25329'], ['42605'], ['428240849'], ['5101'], ['568'], ['570716'], ['57116'], ['57080545404'], ['57083134076']]], ['Tags', ['Stock', 'Color', 'Fam', 'Dress','Maxi']], ['Type', ['Luxary']], ['Vendor', ['AAA']]]"

l = ast.literal_eval(s)
d = dict(l)
{'Categories': [['180972'],
  ['180800'],
  ['16228'],
  ['32733'],
  ['32789'],
  ['32833'],
  ['325137'],
  ['32839'],
  ['25329'],
  ['42605'],
  ['428240849'],
  ['5101'],
  ['568'],
  ['570716'],
  ['57116'],
  ['57080545404'],
  ['57083134076']],
 'Tags': ['Stock', 'Color', 'Fam', 'Dress', 'Maxi'],
 'Type': ['Luxary'],
 'Vendor': ['AAA']}

如果您还想摆脱内部列表,请使用the other answer,而不是只调用对象上的dict。你知道吗

相关问题 更多 >