python Dictionary One Click Multi Valued Instance Code Sharing

  • 2021-06-28 13:14:28
  • OfStack

A dictionary in python can have multiple values with one key, meaning that one key can correspond to multiple values.

Example:


#encoding=utf-8

 

print ' China '

 

# Dictionary 1 Key Multivalue 

 

print' programme 1 list As dict Value of   Value allows duplication ' 

 

d1={}

key=1

value=2

d1.setdefault(key,[]).append(value)

value=2

d1.setdefault(key,[]).append(value)

 

print d1

 

# Get value 

print ' programme 1  Get value '

print list(d1[key])

 

print ' programme 1  Delete value, leaving 1 Empty list '

d1[key].remove(value)

d1[key].remove(value)

print d1 

 

print ' programme 1  Check if there are any more 1 Values '

print d1.get(key,[])

 

print ' programme 2  Use a subdictionary as the dict Value of   Value does not allow duplication '

 

d1={}

key=1

keyin=2

value=11

d1.setdefault(key,{})[keyin]=value

keyin=2

value=22

d1.setdefault(key,{})[keyin]=value

keyin=3

value=33

d1.setdefault(key,{})[keyin]=value

 

print d1

 

print ' programme 2  Get value '

print list(d1[key])

 

print ' programme 2  Delete value, leaving 1 Empty list '

del d1[key][keyin]

keyin=2

del d1[key][keyin]

print d1

 

print ' programme 2  Check if there are any more 1 Values '

print d1.get(key,())

 

print ' programme 3  Use set As dict Value of   Value does not allow duplication '

d1={}

key=1

value=2

d1.setdefault(key,set()).add(value)

value=2

d1.setdefault(key,set()).add(value)

value=3

d1.setdefault(key,set()).add(value)

 

print d1

 

print ' programme 3  Get value '

print list(d1[key])

 

print ' programme 3  Delete value, leaving 1 Empty list '

d1[key].remove(value)

value=2

d1[key].remove(value)

print d1 

 

print ' programme 3  Check if there are any more 1 Values '

print d1.get(key,())

The printout is as follows:


 China 

 programme 1 list As dict Value of   Value allows duplication 

{1: [2, 2]}

 Get value 

[2, 2]

 Delete value, leaving 1 Empty list 

{1: []}

 Check if there are any more 1 Values 

[]

 programme 2  Use a subdictionary as the dict Value of   Value does not allow duplication 

{1: {2: 22, 3: 33}}

 Get value 

[2, 3]

 Delete value, leaving 1 Empty list 

{1: {}}

 Check if there are any more 1 Values 

{}

 programme 3  Use set As dict Value of   Value does not allow duplication 

{1: set([2, 3])}

 Get value 

[2, 3]

 Delete value, leaving 1 Empty list 

{1: set([])}

 Check if there are any more 1 Values 

set([])

This is all the example code of python Dictionary 1 key multi-value introduced here. Thank you for your learning and support for this site.


Related articles: