📜  在Python中创建集合字典

📅  最后修改于: 2022-05-13 01:55:51.816000             🧑  作者: Mango

在Python中创建集合字典

在本文中,我们将讨论如何在Python中创建集合字典。

方法1:朴素的方法

我们可以通过将集合作为值传递给键来创建集合字典。

句法:

示例:为学生详细信息创建集合字典的Python程序

Python3
# create  dictionary of sets for student details
data = {'Student Roll-no': {1, 2, 3, 4, 5},
        'Student Aadhar No': {11, 22, 33, 44, 55}}
  
  
# display
print(data)


Python3
# create  dictionary of sets for student details
data = {'Student Roll-no': {1, 2, 3, 4, 5, 1, 2, 3, 2},
        'Student Aadhar No': {11, 22, 33, 44, 55, 22,
                              33, 44, 11}}
  
  
# display
print(data)


Python3
# import defaultdict module
from collections import defaultdict
  
# create an empty set of dictionary
dictionary = defaultdict(set)
  
# enter key value pair 1
dictionary["Student Roll-no"] |= {1, 2, 3, 4, 5}
  
# ennter key value pair 2
dictionary["Student Aadhar No"] |= {11, 22, 33, 44, 55}
  
# display
dictionary


Python3
# Dictionary with student data
data = {'Student No': {1, 2, 3, 4, 5},
        'Student Aadhar No': {11, 22, 33, 44, 55}}
  
# using setdefault() method to get aadhar number
# of the students
print(data.setdefault('Student Aadhar No'))
  
# using setdefault() method to get aadhar number
# of the students
print(data.setdefault('Student No'))
  
# set the third set using setdefault method for 
# student names
data = data.setdefault(
    'Student Names', {'sravan', 'gopi', 'ramya',
                      'durga', 'sudheer'})
  
# display
data


输出:

根据定义,集合不允许重复。

示例 2:显示不允许重复的Python程序

Python3

# create  dictionary of sets for student details
data = {'Student Roll-no': {1, 2, 3, 4, 5, 1, 2, 3, 2},
        'Student Aadhar No': {11, 22, 33, 44, 55, 22,
                              33, 44, 11}}
  
  
# display
print(data)

输出:

方法2:使用defaultdict方法

在这里,在这种方法中,我们将创建一个默认集,然后将键值传递给它。

句法:

使用键和值传递字典的语法:

在哪里,

  • dictionary_name 是输入字典
  • 关键是关键
  • 值是集合

示例:用于创建学生数据集字典的Python代码

Python3

# import defaultdict module
from collections import defaultdict
  
# create an empty set of dictionary
dictionary = defaultdict(set)
  
# enter key value pair 1
dictionary["Student Roll-no"] |= {1, 2, 3, 4, 5}
  
# ennter key value pair 2
dictionary["Student Aadhar No"] |= {11, 22, 33, 44, 55}
  
# display
dictionary

输出:

方法 3:使用setdefault() 方法

setdefault() 方法返回字典中键的值。如果没有,它会在字典中插入一个带有值的键。

句法:

在哪里,

  • key - 在字典中搜索的键。
  • default_value 是特定键的值

示例:将学生姓名集插入字典的Python程序

Python3

# Dictionary with student data
data = {'Student No': {1, 2, 3, 4, 5},
        'Student Aadhar No': {11, 22, 33, 44, 55}}
  
# using setdefault() method to get aadhar number
# of the students
print(data.setdefault('Student Aadhar No'))
  
# using setdefault() method to get aadhar number
# of the students
print(data.setdefault('Student No'))
  
# set the third set using setdefault method for 
# student names
data = data.setdefault(
    'Student Names', {'sravan', 'gopi', 'ramya',
                      'durga', 'sudheer'})
  
# display
data

输出: