How can I create a dictionary out of a .txt file with this specific data structure?

85 views Asked by At

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
  }
}
2

There are 2 answers

0
Yossi Levi On BEST ANSWER

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'}}
1
Ashish Gupta On

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