如何在python中访问嵌套字典键的值?

时间:2015-06-13 10:40:14

标签: python class dictionary

我有嵌套字典,我想更新第二个字典'键'值的值,这样它也应该反映字典值。

class Screen_Seat:
   def __init__(self,screen,show,num_seats,day):
      self.screen_id = screen
      self.show = show
      self.num_seats = num_seats

     self.seats = {('screen1','day4'):{'show1':100,'show2':100,'show3':100,'show4':100},
                   ('screen1','day5'):{'show1':100,'show2':100,'show3':100,'show4':100},
                   ('screen1','day6'):{'show1':100,'show2':100,'show3':100,'show4':100},
                   ('screen1','day7'):{'show1':100,'show2':100,'show3':100,'show4':100},}

我想更新以下密钥的值

self.seats['screen1','day4','show4'] =90

这样:

self.seats = {('screen1','day4'):{'show1':100,'show2':100,'show3':100,'show4':**90**},
                       ('screen1','day5'):{'show1':100,'show2':100,'show3':100,'show4':100},
                       ('screen1','day6'):{'show1':100,'show2':100,'show3':100,'show4':100},
                       ('screen1','day7'):{'show1':100,'show2':100,'show3':100,'show4':100},}

我怎么能在python中做到这一点?

修改

class Screen_Seat:
   def __init__(self,screen,show,num_seats,day):
      self.screen_id = screen
      self.show = show
      self.num_seats = num_seats

      self.seats = {('screen1','day4'):{'show1':100,'show2':100,'show3':100,'show4':100},
      ('screen1','day5'):{'show1':100,'show2':100,'show3':100,'show4':100},
      ('screen1','day6'):{'show1':100,'show2':100,'show3':100,'show4':100},
      ('screen1','day7'):{'show1':100,'show2':100,'show3':100,'show4':100},
          ('screen2','day1'):{'show1':100,'show2':100,'show3':100,'show4':100},
      ('screen2','day2'):{'show1':100,'show2':100,'show3':100,'show4':100},
      ('screen2','day3'):{'show1':100,'show2':100,'show3':100,'show4':100},
                     }

class Screen_Booking(screen_seat):
   def __init__(self,screen,show,num_seats,day):
       screen_seat.__init__(self,screen,show,num_seats,day)
       self.booking_screen = screen
       self.booking_show = show
       self.booking_day=day
       self.booking_seats=num_seats

   def CheckAvailability(self):
       self.seats[self.booking_screen,self.booking_day][self.booking_show]
       if (self.seats[self.booking_screen,self.booking_day][self.booking_show] > int(self.booking_seats)):
          self.seats[self.booking_screen,self.booking_day][self.booking_show]=(self.seats[self.booking_screen,self.booking_day][self.booking_show]-int(self.booking_seats))

          #print self.seats[self.booking_screen,self.booking_day][self.booking_show]
          print 'seat booked'
       else:
           print 'Sorry, No seats available in Screen1. Please try other Screens'


A1 = Screen_Booking('screen1','show1','98','day4')
A1.CheckAvailability()
A1 = Screen_Booking('screen1','show1','10','day4')

输出:

2
seat booked
90
seat booked

第二次打印'抱歉,Screen1中没有座位。请尝试其他屏幕

帮我识别代码中的问题?

2 个答案:

答案 0 :(得分:1)

您的词典有两个嵌套级别,一个用('screenX', 'dayX')元组索引,另一个用showX字符串索引。请注意以下事项:

>>> foo.seats['screen1', 'day4']
{'show4': 90, 'show2': 100, 'show1': 100, 'show3': 100}
>>> foo.seats['screen1', 'day4']['show4']
90

第一个表达式为您提供了一个字典,您必须再次索引才能获得所需的元素。所以最后的表达是:

foo.seats['screen1', 'day4']['show4']
#         ^                  ^
#         |                  |
#         +-- First level    +-- Second level

答案 1 :(得分:1)

使用此:

self.seats[('screen1', 'day4')]['show4'] = 90

<强>输出:

self.seats
{('screen1', 'day4'): {'show1': 100, 'show2': 100, 'show3': 100, 'show4': 90},
 ('screen1', 'day5'): {'show1': 100, 'show2': 100, 'show3': 100, 'show4': 100},
 ('screen1', 'day6'): {'show1': 100, 'show2': 100, 'show3': 100, 'show4': 100},
 ('screen1', 'day7'): {'show1': 100, 'show2': 100, 'show3': 100, 'show4': 100}}

首先访问screen {day4'显示('screen1', 'day4')元组作为self.seats字典中的键。然后按'show4'访问内部字典的'show4'键,并将其值设置为90.

你似乎是python的新手。让我们尝试通过以下3个步骤来理解思考过程。

<强>步骤1:

('screen1', 'day4')可以访问{'show1': 100, 'show2': 100, 'show3': 100, 'show4': 100}内部词典。

self.seats[('screen1', 'day4')]
{'show1': 100, 'show2': 100, 'show3': 100, 'show4': 100}

<强>步骤2:

现在,通过前一步骤中获取的字典中的show4键访问'show4'

self.seats[('screen1', 'day4')]['show4']
100

<强>步骤3:

将screen1-day4-show4获得的值更新为90。

self.seats[('screen1', 'day4')]['show4'] = 90

self.seats[('screen1', 'day4')]['show4']
90

代码解决方案:

检查此方法是否适合您。

class ScreenBooking(object):

    def __init__(self):
        super(ScreenBooking, self).__init__()
        self.seats = {
            ('screen1','day4'):{'show1':100,'show2':100,'show3':100,'show4':100},
            ('screen1','day5'):{'show1':100,'show2':100,'show3':100,'show4':100},
            ('screen1','day6'):{'show1':100,'show2':100,'show3':100,'show4':100},
            ('screen1','day7'):{'show1':100,'show2':100,'show3':100,'show4':100},
            ('screen2','day1'):{'show1':100,'show2':100,'show3':100,'show4':100},
            ('screen2','day2'):{'show1':100,'show2':100,'show3':100,'show4':100},
            ('screen2','day3'):{'show1':100,'show2':100,'show3':100,'show4':100},
        }
        self.shows = ['show1', 'show2', 'show3', 'show4']


    def check_valid_details(self, screen, show, day):
        """
        Check if booking details are valid and return True/False accordingly.
        """
        if (screen, day) not in self.seats or show not in self.shows:
            return  False
        return True

    def book_seats(self, screen, show, no_of_seats, day):
        """
        Book seats after checking valid booking details and the remaining seats.
        """
        valid_details = self.check_valid_details(screen, show, day)
        if not valid_details:
            print 'Invalid booking details!'
            return
        show_total_seats = self.seats[(screen, day)][show]
        if show_total_seats > int(no_of_seats):
            show_remaining_seats = show_total_seats - int(no_of_seats)
            self.seats[(screen, day)][show] = show_remaining_seats #update the seats count
            print '%s seat(s) booked'%(no_of_seats)
        else:
            print 'Sorry, No seats available in %s. Please try other Screens'%(screen)

a1 = ScreenBooking()
a1.book_seats('screen1','show1','98','day4')
a1.book_seats('screen1','show1','10','day4')