python-3.x 我可以在字典中放置一个变量吗?

plicqrtu  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(90)

我想把一个名为Theo_Skutar_contact的字典中的变量放在另一个名为all_contact_dictionary的字典的值中。这是我的代码,请帮我弄清楚,因为这是我爸爸的工作项目。你输入一个名字,它会搜索联系人。在这种情况下,我使用了西奥多Skutar。

all_contact_dictionary = {
    "First Last": First_Last_contact,
}

First_Last_contact = {
    "First Name": "First",
    "Nickname": "Nick",
    "Last Name": "Last",
    "Company": "WorkingInc",
}

while True:
  name_input = input("Type first and last name here with capitals. Don't type nicknames.  ")

  if name_input in all_contact_dictionary:
    print(all_contact_dictionary[name_input])
  else:
    print("Not found. Try again.")

字符串
在第一个字典中是我想在第二个值中链接它的地方。
我试着做“,我试着不做“,我试着做”,但都不起作用。

8iwquhpp

8iwquhpp1#

这就是你想做的吗?
尽管我建议从这里开始学习类和对象。

theo_skutar_contact = {
    "First Name": "Theodore",
    "Nickname": "Theo",
    "Last Name": "Skutar",
    "Company": "SomeCompany",
}

dave_murray_contact = {
    "First Name": "David",
    "Nickname": "Dave",
    "Last Name": "Murray",
    "Company": "Iron Maiden",
}

all_contact_dictionary = {
    "Theodore Skutar": theo_skutar,
    "David Murray": dave_murray_contact,
}

while True:
  name_input = input("Type first and last name here with capitals. Don't type nicknames.  ")

  if name_input in all_contact_dictionary:
    print(all_contact_dictionary[name_input])
  else:
    print("Not found. Try again.")

>> {'First Name': 'Theodore', 'Nickname': 'Theo', 'Last Name': 'Skutar', 'Company': 'SomeCompany'}

字符串
使用数据类的示例

from dataclasses import dataclass

@dataclass
class Contact:
    first_name: str
    last_name: str
    nickname: str 
    company: str

theo_skutar = Contact(first_name = "Theodore", last_name = "Skutar", nickname= "Theo", company = "CompanyA")
dave_murray = Contact(first_name = "David", last_name = "Murray", nickname= "Dave", company = "Iron Maiden")

all_contact_dictionary = {
    "Theodore Skutar": theo_skutar,
    "David Murray": dave_murray,
}

while True:
  name_input = input("Type first and last name here with capitals. Don't type nicknames.  ")

  if name_input in all_contact_dictionary:
    print(all_contact_dictionary[name_input])
    print(all_contact_dictionary[name_input].nickname)
  else:
    print("Not found. Try again.")

>>> Contact(first_name='Theodore', last_name='Skutar', nickname='Theo', company='CompanyA')
>>> Theo

相关问题