How to print either 1 specific value, or a select key2 values for all key1 from a nested dictionary? The lines in my code display nothing.
Foe example , how to print (a single value):
Canon-PS-G7-X-Mark-II`
or (select key2 values for all key1):
Canon-PS-G7-X-Mark-II
Nikon-D5
Sony-alpha9
The dictionary (part of it) and code
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)
try below code:
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))
output:
1 camera:
(Canon-PS-G7-X-Mark-II)
all cameras
(['Canon-PS-G7-X-Mark-II', 'Nikon-D5', 'Sony-alpha9'])
I am sure someone else can do better than I.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.