如何使用正则表达式和 defaultdict 创建带有列表的字典

How to create dictionary with list with regex and defaultdict

字典在下面

my = [{'Name':'Super', 'Gender':'Male', 'UNNO':111234},
      {'Name':'Spider', 'Gender':'Male', 'UNNO':11123},
      {'Name':'Bat', 'Gender':'Female', 'UNNO':113456},
     {'Name':'pand', 'Gender':'Female', 'UNNO':13456}]

唯一编号是每个字典的键 "UNNO" 的值。

所有 UNNO 号码必须包含 6 位数字。

UNNO号码只从11开始有效

预计结束

my_dict_list = {'Male':['Super'], 'Female':['Bat']}

没有正则表达式的原始代码

d = {}
for i in my:
    if str(i['UNNO']).startswith('11') and len(str(i['UNNO'])) == 6:
        # To get {'Male':['Super'], 'Female':['Bat']}
        d[i['Gender']] = [i['Name']]

How to write help of regex,写正则表达式,如何用defaultdict完成

import re
from collections import defaultdict

# regular expression
rx = re.compile(r'^(?=\d{6}$)(?P<Male>11\d+)|(?P<Female>11\d+)')

# output dict
output = defaultdict(list)

要使用正则表达式匹配来解决您的问题 - 使用以下方法:

import re
from collections import defaultdict

my_list = [{'Name': 'Super', 'Gender': 'Male', 'UNNO': 111234},
           {'Name': 'Spider', 'Gender': 'Male', 'UNNO': 11123},
           {'Name': 'Bat', 'Gender': 'Female', 'UNNO': 113456},
           {'Name': 'pand', 'Gender': 'Female', 'UNNO': 13456}]

genders = defaultdict(list)
pat = re.compile(r'^11\d{4}$')  # crucial pattern to validate `UNNO` number

for d in my_list:
    if pat.search(str(d['UNNO'])):
        genders[d['Gender']].append(d['Name'])

print(dict(genders))   # {'Male': ['Super'], 'Female': ['Bat']}