-1

The txt file i'm working with contains something like this:

[
  {
    "Data": "asdf",
    "Monday": "321.247",
    "Tuesday": "27.801",
    "Thursday": "35.235"
  },
  {
    "Data": "whatever",
    "Monday": "321.247",
    "Tuesday": "207.568",
    "Thursday": "31.027",
    "Wednesday": "56.902"
  }
]

I'd like to create a dictionary with the same structure so I can re-organize it with the "Data" field as the first level key with the week days as the second level keys and the numerical values as the values. I have tried importing it with json library but I don't really know what to do next as all I can create with it is a list.

EDIT:

When doing:

with open(".../file.txt") as file:
  data=json.load(file)

type(data)

I get:

list

What I expect to get is a dictionary like:

data
{
  "asdf" : {
    "Monday": 321.247,
    "Tuesday": 27.801,
    "Thursday": 35.235
  },
"whatever": {
    "Monday": 321.247,
    "Tuesday": 207.568,
    "Thursday": 31.027,
    "Wednesday": 56.902
  }
}
cYbersYn
  • 13
  • 3
  • 1
    Have you tried `import json` and calling `json.load`? – imrek Oct 03 '20 at 19:13
  • 1
    1) What have you tried so far, and where are you stuck? 2) What is the output you’re expecting? Please update the *question* with both. – S3DEV Oct 03 '20 at 19:15
  • Please [edit] your question and add the code of your attempt to it. Note that those "numerical values" are strings not numbers. – martineau Oct 03 '20 at 19:21
  • Your code with `data=json.load(file)` works well. You txt file contains list of jsons. How do you expect to convert them to one dictionary? Please add your expected dictionary structure. – Gabio Oct 03 '20 at 19:42

2 Answers2

0

It's a bit tricky using this nested dict comprehension, but think of it a bit and you figure it out (feel free to ask for more explanation..), efficiency-wise I think it the best approach:

a = [
  {
    "Data": "asdf",
    "Monday": "321.247",
    "Tuesday": "27.801",
    "Thursday": "35.235"
  },
  {
    "Data": "whatever",
    "Monday": "321.247",
    "Tuesday": "207.568",
    "Thursday": "31.027",
    "Wednesday": "56.902"
  }
]

modified_a = {item["Data"]:{key:val for key,val in item.items() if key!="Data"} for item in a}

print(modified_a)

output:

{'asdf': {'Monday': '321.247', 'Tuesday': '27.801', 'Thursday': '35.235'}, 'whatever': {'Monday': '321.247', 'Tuesday': '207.568', 'Thursday': '31.027', 'Wednesday': '56.902'}}
Yossi Levi
  • 1,258
  • 1
  • 4
  • 7
-1

You can make use of eval which will create dictionary after reading from file

with open('test', 'r') as reader:
    d = eval(reader.read())
print(d)

output:

[{'Data': 'asdf', 'Monday': '321.247', 'Tuesday': '27.801', 'Thursday': '35.235'}, {'Data': 'whatever', 'Monday': '321.247', 'Tuesday': '207.568', 'Thursday': '31.027', 'Wednesday': '56.902'}]
# using above data structure you can create your leveled key as you want 
Ashish Gupta
  • 372
  • 1
  • 4
  • 11