Note that there are some explanatory texts on larger screens.

plurals
  1. POZip two lists of unequal length to form a dictionary. Values to be randomly picked from one of the lists
    primarykey
    data
    text
    <p>[Using Python 3.x] I'm trying to create a CSV file with two columns, one containing fake e-mail addresses, the second column should contain a certain country code as specified in the respective function.</p> <p>I would like the country codes to be - at least - uniformly distributed assigned to each e-mail address. But it would be great if there was also a way that they were not uniformly distributed. For instance where one country could would be assigned to 30% of the e-mail addresses, another one 10%, etc.</p> <p>My biggest struggle is with creating a dictionary where the key is the e-mail address and the value the country code, and thus zipping two lists that have unequal length and not having empty values (None). On a side note, I thought creating a dictionary would be the best way to do so, but I'm very new to programming and python and hence if you have a better solution please do share!!</p> <p>This is my code:</p> <pre><code>from random import choice, randint from string import ascii_lowercase from itertools import zip_longest import csv def gen_name(length): """"Generates a random name with the given amount of characters.""" return ''.join(choice(ascii_lowercase) for i in range(length)) def email_gen(): """Generates a fake email address.""" user = gen_name(randint(5, 10)) host = gen_name(randint(5, 15)) return user + "@" + host + ".com" def gen_plain_email_list(n): """Generates a list of n amount of random e-mail addresses""" emaillist = [] for i in range(n): emaillist.append(email_gen()) return emaillist def gen_email_dict(n): """Generates a dictionary where the key is an e-mail address and the value a random country code.""" email_list = [] cc = ['us', 'gb', 'de', 'fr', 'it', 'nl', 'es', 'ae', 'br', 'au'] # Creating a list of n amount of e-mail addresses for i in range(n): email_list.append(email_gen()) # Creates dictionary with with an e-mail address from email_list and # a random country code from the cc list email_dict = dict(zip_longest(email_list, cc, fillvalue=choice(cc))) return email_dict def dict_to_csv(filename, n): with open(filename, 'w', newline='') as f: w = csv.writer(f) w.writerows(gen_email_dict(n).items()) dict_to_csv('test.csv', 1000) </code></pre> <p>Thanks in advance for the help!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload