简体   繁体   English

将带有字典的列表转换成字典

[英]Converting list with dictionary inside to dictionary

I have looked on stack-overflow for an answer to this question (and beyond!). 我已经在堆栈溢出中寻找了这个问题的答案(以及以后的答案!)。 However most of them raised errors that, to fix, I would have to change the entire json. 但是,其中大多数引发了错误,要修复,我将不得不更改整个json。 This probably is not the best way, but, what I did is get a json that is REALLY long. 这可能不是最好的方法,但是,我所做的是获取一个非常长的json。 I then parsed the first time it and got this: 然后,我第一次对其进行了解析,并得到了以下信息:
[{'food': 'eat'}, {'food': 'eat out'}, {'food': 'go to dinner'}, {'food': 'go to lunch'}, {'food': 'go to breakfast'}, {'food': 'go out'}, {'food': 'eat out'}] . [{'food': 'eat'}, {'food': 'eat out'}, {'food': 'go to dinner'}, {'food': 'go to lunch'}, {'food': 'go to breakfast'}, {'food': 'go out'}, {'food': 'eat out'}]
The only problem is that when I parse it the second time, it converts to a list. 唯一的问题是,当我第二次解析它时,它将转换为列表。 I have tried multiple ways of fixing this, but have found none that work. 我尝试了多种解决此问题的方法,但没有找到任何可行的方法。 Here is an example of my code: 这是我的代码示例:

# location is location of json, called JoeLearn.json

with open(location) as f:
    data = json.load(f)
for checks in range(len(['food'])): # I will replace ['food'] with a variable with more data in it. 
    data['food']
    # Code to convert to list

After I do data['food'] it looks like this (same as before): 在我完成data['food']它看起来像这样(与之前相同):
[{'food': 'eat'}, {'food': 'eat out'}, {'food': 'go to dinner'}, {'food': 'go to lunch'}, {'food': 'go to breakfast'}, {'food': 'go out'}, {'food': 'eat out'}] . [{'food': 'eat'}, {'food': 'eat out'}, {'food': 'go to dinner'}, {'food': 'go to lunch'}, {'food': 'go to breakfast'}, {'food': 'go out'}, {'food': 'eat out'}]
How can I turn this into a dictionary so I can preform .keys() on it? 如何将其变成字典,以便可以在其上执行.keys() If you have questions, please leave a comment. 如有疑问,请发表评论。 If you have an answer, please add it to the answers, as so many people leave answers in the comments. 如果您有答案,请将其添加到答案中,因为很多人在评论中留下答案。

Thanks in advance, 提前致谢,
- User 9297446 -用户9297446

Maybe this helps: 也许这会有所帮助:

with open(location) as f:
    data = json.load(f)
food_list = [x['food'] for x in data] #find all value that with 'food' as key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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