【发布时间】:2018-03-21 22:42:38
【问题描述】:
我在这方面工作太久了,需要一些帮助。 我正在尝试使用faker创建字典。要是就这么简单就好了。 最初字典是扁平的。钥匙和物品。如果键的第一个字母是“B”或“M”,它将将该字符串转换为具有 5 个键的字典并继续执行此操作,直到找不到以这两个字母中的任何一个开头的字母。我知道,现在没有递归发生。这就是我需要帮助的原因。我试图弄清楚如何正确递归而不是硬编码深度。
Starting Dictionary:
{
"Marcia": "https://www.skinner.biz/categories/tags/terms.htm",
"Nicholas": "https://scott-tran.com/",
"Christopher": "https://www.ellis.com/",
"Paul": "https://lopez.com/index/",
"Jennifer": "https://www.sosa.com/wp-content/main/login.php"
}
Marcia 应该扩展到这个...
Example:
"Marcia": {
"Alexander": "http://hicks.net/home.html",
"Barry": {
"Jared": "https://www.parker-robinson.com/faq.html",
"Eddie": "https://www.smith-thomas.com/",
"Ryan": "https://www.phillips.org/homepage/",
"Mary": {
"Alex": "http://www.perry.com/tags/explore/post.htm",
"Joseph": "https://www.hansen.com/main/list/list/index/",
"Alicia": "https://www.tran.biz/wp-content/explore/posts/",
"Anna": "http://lee-mclaughlin.biz/search/login/",
"Kevin": "https://blake.net/main/index/"
}
"Evan": "http://carroll.com/homepage.html"
}
"Sharon": "https://www.watson.org/categories/app/login/",
"Hayley": "https://www.parks.com/",
"William": "https://www.wyatt-ware.com/"
}
我的代码是手动的而不是动态的,因为我现在必须明确知道字典的许多层次,而不是动态地找出它。
这是我拥有的 2 个级别的深度,但我想找到任何以“B”或“M”开头的键并对其进行操作。
import json
from build_a_dictionary import add_dic
from faker import Faker
dic = add_dic(10)
dic1 = {}
dic2 = {}
def build_dic(dic_len):
dic1 = {}
fake = Faker()
if len(dic1) == 0:
dic1 = add_dic(dic_len)
print(json.dumps(dic1, indent=4))
for k, v in dic1.items():
dic2[k] = add_dic(dic_len)
for key in dic2[k].keys():
for f in key:
if f == 'B' or f == 'M':
dic2[k][key] = add_dic(dic_len)
return dic2
这是我写的 add_dic() 的代码:
import string, time
from faker import Faker #had to install with pip
fake = Faker()
dic = {}
dics = {}
key = ""
def add_dic(x):
dic={}
start = time.time()
if x > 690:
print("Please select a value under 690")
sys.exit()
for n in range(x):
while len(dic) < x:
key = fake.first_name()
if key in dic.keys():
break
val = fake.uri()
dic[key] = val
end = time.time()
runtime = end - start
return dic
【问题讨论】:
-
嵌套名称从何而来?
-
字典中的所有数据都来自 add_dic()。