Python:如何将JSON中的值设置为列表中的索引?
我试图读取一个数据集,并将JSON文件的整数值设置为列表的数组。这是示例JSON文件Python:如何将JSON中的值设置为列表中的索引?,python,json,list,Python,Json,List,我试图读取一个数据集,并将JSON文件的整数值设置为列表的数组。这是示例JSON文件 [{ "index_id": "1234", "text": "hello world", }, { "index_id": "5678", "text": "roses are red", }] 现在,我刚刚尝试读取JSON文件并将所有内容放入defaultdict(列表),这会把事情搞砸。假设我把所有内容都读给L1 如果我尝试获取L1[1234]这将给出一个错误,因为1234不是L1中的有效索引,索引为0
[{
"index_id": "1234",
"text": "hello world",
},
{
"index_id": "5678",
"text": "roses are red",
}]
现在,我刚刚尝试读取JSON文件并将所有内容放入defaultdict(列表),这会把事情搞砸。假设我把所有内容都读给L1
如果我尝试获取L1[1234]这将给出一个错误,因为1234不是L1中的有效索引,索引为0,1
如果打印L1
{u'1234': u'hello world'}, {u'5678': u'roses are red'}]
我知道列表中有我的潜在索引值,作为存储在unicode中的值(更糟)
那么如何将L1转换为一种方法,如果我尝试拉起L1[1234],它会拉起“hello world”
{1234: u'hello world'}, {5678: u'roses are red'}]
多谢各位
编辑:更改JSON。假设您有一个DICT列表,您可以执行以下操作:
json_lst = [{
"1234": "hello world"
},
{
"5678": "roses are red"
}]
result = {int(k) : v for element in json_lst for k, v in element.items()}
print(result[1234])
输出
hello world
上述字典理解相当于以下嵌套循环:
result = {}
for element in json_lst:
for k, v in element.items():
result[int(k)] = v
或者尝试合并字典列表:
>>> [i['1234'] for i in L1 if '1234' in i][0]
'hello world'
>>>
整件事:
>>> L1=[{
"1234": "hello world"
},
{
"5678": "roses are red"
}]
>>> [i['1234'] for i in L1 if '1234' in i][0]
'hello world'
>>>
我认为您可以将其作为python字典阅读,其中1234和5678是“键”,相应的字符串是值。 比如说,
{
1234: 'hello world',
5678: 'roses are red'
}
如您所述,您可以索引到它,L1[1234]
,您将得到“hello world”。
你可以读一些关于字典的书 像这样更改json
L1 = {
"1234": "hello world",
"5678": "roses are red"
}
# call it with quote or as string
print L1["1234"]
或创建函数
jsonList = [{
"1234": "hello world"
},
{
"5678": "roses are red"
}]
def L1(key):
key = str(key)
for i in jsonList:
if key in i:
return i[key]
print L1(5678)
如果您是从json文件读取数据,则加载json时,数据类型为dictionary,您可以直接读取加载数据的键。 如果你想创建一个列表,请参考下面的代码 mysample.json文件 { "1234": { “id”:“blabla”, “iscategorical”:“0” }, "5678": { “id”:“valore” }, “8975”:“价值”, "6985": { “id”:“valore” } } 单独python文件中的代码: 导入json 输入io 从集合导入defaultdict 以io.open('sample.json')作为数据文件:
data_loaded = json.load(data_file)
打印(已加载数据)
打印(类型(数据加载))
l1=默认DICT(列表)
对于加载的密钥输入数据:
l1[key] = data_loaded[key]
打印(l1)
打印(l1['1234'])这不是
json
。这是两个不同的dicts/json
的列表,我现在编辑了这个问题。如果您现在可以显示数据集样本。@DanielMesejo?但是您如何获得该dict?这似乎是一个解决方案,它只需对原始数据文件进行最小的更改。谢谢你。