如何将相同的值添加到字典中的不同键?

2024-09-29 22:19:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有2个JSON文件。一份学生档案和一份学生档案。你知道吗

我有一份字典清单,上面有学生的姓名、电子邮件和学生号。你知道吗

我想做的是,如果有60个学生,我想给他们一个唯一的学号。这一部分在elif语句中起作用。我不知道如何实现的部分是:

如果有20个学生,我想给例如2个学生相同的学生号码(这听起来很愚蠢,但我需要它)。在这种情况下,student是键,studentnumber是值。你知道吗

我现在拥有:


# student
[{"Student1":029182,"e-mail":"example@.com"},{"Student2":0591238,"e-mail":"example@.com"},{"Student3":9213189,"e-mail":"example@.com"}]



studentnumbers = [{"studentnumber":"029182","ID":0},{"studentnumber":"0591238","ID":1},{"studentnumber":"9213189","ID":2}]

students = [list(data.values())[0] for data in studentnumbers]


ID = 0
# students is a list of studentnumbers
if len(students) <= 20:
    # studentInfo is my dictionary with the key and values
    for data in studentnumbers:
        try:
            pass

        except IndexError:
            pass



elif len(students) <= 60:
    for data in studentnumbers:
        try:   
            studentnumbers[ID] = students[ID]
            ID += 1
            break
        except IndexError:
            pass
    print("..")
else:
    print("...")

with open('Students.json','w') as instudent:
    json.dump(studentnumbers,instudent,indent=2)


输出我现在拥有的:

[{"Student1":029182,"e-mail":"example@.com","studentnumber":029182},
{"Student2":0591238,"e-mail":"example@.com","studentnumber":9213189},
{"Student3":9213189,"e-mail":"example@.com","studentnumber":0591238},
{"Student4":9213189,"e-mail":"example@.com","studentnumber":0294832},
{"Student5":9213189,"e-mail":"example@.com","studentnumber":0591823},
{"Student6":9213189,"e-mail":"example@.com","studentnumber":0501852}]

我想要的是:

[{"Student1":029182,"e-mail":"example@.com","studentnumber":029182},
{"Student2":0591238,"e-mail":"example@.com","studentnumber":029182},
{"Student3":9213189,"e-mail":"example@.com","studentnumber":029182},
{"Student4":9213189,"e-mail":"example@.com","studentnumber":9213189},
{"Student5":9213189,"e-mail":"example@.com","studentnumber":9213189},
{"Student6":9213189,"e-mail":"example@.com","studentnumber":9213189}]

Tags: incomidfordataexamplemailpass
3条回答

似乎您想有条件地更新一个dict列表。你知道吗

给定的

import random


students = [
    {"Student1": "029182", "e-mail": "ex@mail.com"},
    {"Student2": "0591238", "e-mail": "ex@mail.com"},
    {"Student3": "9213189", "e-mail": "ex@mail.com"},
]

代码

def get_unique_numbers(size=10):
    """Return an a list of unique random values."""
    return random.sample(range(10000, 99999), size)


def update(students):
    """Return a list of updated dicts."""
    n = len(students)

    # Conditionally, generate student numbers
    if n <= 20:
        student_numbers = [students[0]["Student1"]] * n
    elif 20 < n <= 60:
        student_numbers = get_unique_numbers(n)

    # Update dicts w/student numbers
    return [{**d, "student_num": n} for d, n in zip(students, student_numbers)]

演示

一小部分学生(n <= 20)返回具有相同学生编号的dict:

update(students)
# [{'Student1': '029182', 'e-mail': 'ex@mail.com', 'student_num': '029182'},
#  {'Student2': '0591238', 'e-mail': 'ex@mail.com', 'student_num': '029182'},
#  {'Student3': '9213189', 'e-mail': 'ex@mail.com', 'student_num': '029182'}]

较大的列表(n > 20)返回带有随机学生编号的dict*:

update(students * 7)
# {'Student1': '029182', 'e-mail': 'ex@mail.com', 'student_num': 28308},
# {'Student2': '0591238', 'e-mail': 'ex@mail.com', 'student_num': 21986},
# {'Student3': '9213189', 'e-mail': 'ex@mail.com', 'student_num': 36603},
# ...
# {'Student1': '029182', 'e-mail': 'ex@mail.com', 'student_num': 38362},
# {'Student2': '0591238', 'e-mail': 'ex@mail.com', 'student_num': 99305},
# {'Student3': '9213189', 'e-mail': 'ex@mail.com', 'student_num': 78360}

*注意:根据需要实现随机数生成器。这个函数从样本总体返回随机整数。

我个人不喜欢使用字典,我只是认为类对象更方便,尽管在大规模应用中可能更慢。你知道吗

我不知道你的问题是什么,我不知道字典里不可能有两个相同价值的东西。你知道吗

我会这样做的

import random as r

class student():
    def __init__(self,ID,numb):
        self.number = ID
        self.email = 'example@mail.com'
        self.name = 'student{}'.format(numb)

students = []
for i in range(60):
    x = student(r.randint(10000,99999),i)
    students.append(x)
def test():
    ID = 0
    for i in list(students):
        print(i.name,i.number,i.email)

test()

如果你想设置学号,只需改变r.randint位

如果你要用字典的话,希望对你有帮助 如果您有任何问题,请询问:)

可能下面的代码能帮上忙。我得弄明白你不能用025这样的整数。所以我把它改成了弦。你知道吗

# student numbers
studentNunbers = [{"studentnumber": '029182', "ID": 0}, {"studentnumber": '0591238',"ID": 1},{"studentnumber": '9213189', "ID":2}]
# student
studentInfos = [{"Student1":'029182', "e-mail":'example@.com'}, {"Student2":'0591238',"e-mail":'example@.com'},
                {"Student3":'9213189',"e-mail":'example@.com'}, {"Student3":'92189',"e-mail":'example@.com'},
                {"Student2":'0538',"e-mail":'example@.com'}, {"Student2":'238',"e-mail":'example@.com'},
                {"Student2":'0598',"e-mail":'example@.com'}, {"Student2":'08',"e-mail":'example@.com'},]

students = [list(data.values())[0] for data in studentNunbers]

def merge(numRep=1):
    key = "studentnumber"
    stNumberIndex = 0
    iterInd = numRep
    for i in range(len(studentInfos)):
        value = studentNunbers[stNumberIndex][key]
        studentInfos[i][key] = value

        iterInd -= 1
        if iterInd == 0:
            iterInd = numRep
            stNumberIndex += 1

def test():
    if len(studentNunbers) < 20:
        merge(numRep=3)

    elif len(studentNunbers) < 60:
        merge(numRep=1)
    else:
        pass

test()
print(studentInfos)

相关问题 更多 >

    热门问题