1

I have a JSON file containing information as you can see in the attached file: Json File

I need some help creating a "Dictionary of genres" for each director like this: {GenreName: Number} where "Number" corresponds to the amount of films belonging to that genre the director "created".

E.g. checking "Sidney Lumet" the dictionary should be like this: {u'Drama': 2, u'War': 1, u'Adventure': 1, u'Thriller': 2, u'Crime': 1}

Since in the file you can read:

  "Before the Devil Knows You're Dead;2007": {
    "DIRECTORS": [
      "Sidney Lumet"
    ], 
    "GENRES": [
      "Crime", 
      "Drama", 
      "Thriller"
   "Fail-Safe;1964": {
    "DIRECTORS": [
      "Sidney Lumet"
    ], 
    "GENRES": [
      "Adventure", 
      "Drama", 
      "Thriller", 
      "War"

I explained wrongly what I needed in the title. My problem isn't about how to retrieve the information (I know about the json module and I know how to access its elements), but I need help creating that particular dictionary for each director.

4
  • 3
    Possible duplicate of Parsing values from a JSON file in Python Commented Dec 16, 2015 at 18:05
  • See pythons standard libraries, there is a fantastic json library Commented Dec 16, 2015 at 18:09
  • I'm already using the json library to access each element (Directors, Genres and ofc the title, what I'm not being able to do is creating that particular "genres" dictionary - my bad I wrote a wrong title). Commented Dec 16, 2015 at 18:12
  • Where does your data come from? Where do you store your data? In Python source (bad idea), from a file, from a database ...? Commented Dec 16, 2015 at 18:20

1 Answer 1

2

It is not python but algorithmic question. All related to pyhton here is

with open('file.json') as f:    
    data = json.load(f)

Then, you need go through all films and count each genre e.g. :

directors_dict = {}
for film_name, film in data.iteritems():
    for dir in film['DIRECTORS']:
        if not dir in directors_dict:
            directors_dict[dir] = {}
        for genr in film['GENRES']:
            if not genr in directors_dict[dir]:
                directors_dict[dir][genr] = 0
            directors_dict[dir][genr] += 1

 print(directors_dict)

PS: I am not tested this code, I even don't know exactly what format is (your file needs access from google drive). You should debug and correct mistakes using print() or debugger.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes you were right, anyways my question was both algorithmic and about python (I wasn't sure I could've been able to write the code in python by myself). Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.