从嵌套字典打印

时间:2017-11-13 05:31:47

标签: python python-3.x dictionary

如何从嵌套字典中打印 1特定值或所有key1 的select key2值?我的代码中的行没有显示任何内容。

敌人示例,如何打印(单个值):

Canon-PS-G7-X-Mark-II` 

或(选择所有key1的key2值):

Canon-PS-G7-X-Mark-II
Nikon-D5
Sony-alpha9

字典(部分)和代码

config = {
    'g7': {},
    'd5': {},
    'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')

camtype = """
1 camera:
(config['g7']['cam_name'])

all cameras
(config[.]['cam_name'])

"""
print(camtype)

2 个答案:

答案 0 :(得分:2)

尝试以下代码:

config = {
'g7': {},
'd5': {},
'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')
camtype = """
1 camera:
({0})

all cameras
({1})

"""
single_camera = config['g7']['cam_name']
all_camera = ', '.join([config[k]['cam_name'] for k in config])
print(camtype.format(single_camera, all_camera))

输出:

1 camera:
(Canon-PS-G7-X-Mark-II)

all cameras
(['Canon-PS-G7-X-Mark-II', 'Nikon-D5', 'Sony-alpha9'])

答案 1 :(得分:1)

我相信别人可以做得比我好。

config = {
    'g7': {},
    'd5': {},
    'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')

camtype = """1 camera: %s""" %(config['g7']['cam_name']) #search up python print function
allcam = [ value['cam_name'] for key, value in config.items()] #creates list with all cameras
str_allcam = "all cameras " + ', '.join( str(p) for p in allcam) # prints all cameras with a comma seperator

print(camtype +"\n" + str_allcam) # outputs a two lines because of newline seperator