0

I am searching for a different way to access every key in a dictionary within a for loop. Underneath, there is an example code, where I iterate through a dictionary and access every key with the help of a counter and a if statement. Is there another way to access the keys, without a counter or an if statement?

def string_to_dict(csv):
    dict = []
    tmp = csv.splitlines()
    
    for i in tmp:
        tmp_dict = {"vorname" : "none", "nachname" : "none", "email" : "none"};
        tmp_i= i.split(",")
        counter = 0;

        for si in tmp_i:
            if counter ==0:
                tmp_dict["vorname"] = si
                counter =counter + 1
            elif counter == 1:
                tmp_dict["nachname"] = si
                counter = counter + 1
            else:
                tmp_dict["email"] = si
        dict.append(tmp_dict)
csv = """Donald,Duck,d.duck@entenhausen.com
    Wiley,Coyote,whiley@canyon.org
    Road,Runner,roadrunner@canyon.org"""
  • Maybe [`csv.DictReader`](https://docs.python.org/3/library/csv.html#csv.DictReader) could be useful for you – Ralf Mar 27 '21 at 10:42
  • also, using `dict` as variable name is not good because it overrides the built-in `dict` – Ralf Mar 27 '21 at 10:43
  • As already suggested, if you're manipulating a CSV file, use the standard library's [csv](https://docs.python.org/3/library/csv.html#module-csv) module. It's easier than trying to do all the parsing yourself, and takes care properly of all possible problems of quoting and so on. – Thierry Lathuille Mar 27 '21 at 10:47

3 Answers3

1

If you want minimal changes to what you have done so far, you can just get list of keys and use the index value (counter variable in your case), something like this:

for i in tmp:
    tmp_dict = {"vorname" : "none", "nachname" : "none", "email" : "none"};
    tmp_i= i.split(",")
    counter = 0;
    keys = [*temp_dict.keys()]    # List of Keys
    for si in tmp_i:
        tmp_dict[keys[counter]] = si  # Key at index counter
        counter += 1
    dict.append(tmp_dict)

Sample Run:

>>string_to_dict(csv)
[{'vorname': '    Road', 'nachname': 'Runner', 'email': 'roadrunner@canyon.org'}, {'vorname': '    Road', 'nachname': 'Runner', 'email': 'roadrunner@canyon.org'}, {'vorname': '    Road', 'nachname': 'Runner', 'email': 'roadrunner@canyon.org'}]

Another Note: You're naming the variable as dict You should avoid that since it's a keyword in Python

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
1

There is no need for the loop if you already expect name, surname and email.

def string_to_dict(csv):
    dict = []
    tmp = csv.splitlines()
    
    for i in tmp:
        tmp_dict = {"vorname" : "none", "nachname" : "none", "email" : "none"};
        tmp_i= i.split(",")

        tmp_dict["vorname"] = tmp_i[0]
        tmp_dict["nachname"] = tmp_i[1]
        tmp_dict["email"] = tmp_i[2]

        dict.append(tmp_dict)

We can keep iterating to improve the solution:

def string_to_dict(csv):
    dict = []
    tmp = csv.splitlines()
    
    for i in tmp:
        tmp_dict = {"vorname" : None, "nachname" : None, "email" : None};
        tmp_i= i.split(",")

        tmp_dict["vorname"] = tmp_i[0]
        tmp_dict["nachname"] = tmp_i[1]
        tmp_dict["email"] = tmp_i[2]

        dict.append(tmp_dict)

And even more (if you want to use a protected keyword like dict, naming convention is to use an underscore after it):

def string_to_dict(csv):
    dict_ = []
    for line in csv.splitlines():
        vor_name, nach_name, email = line.split(",")
        dict_.append({"vorname" : vor_name, "nachname" : nach_name, "email" : email})
    return dict_

And with list comprehensions:

def string_to_dict(csv):
    def _parse_item(vor_name, nach_name, email):
        return {"vorname" : vor_name, "nachname" : nach_name, "email" : email}
    return [_parse_item(*line.split(",")) for line in csv.splitlines()]
miquelvir
  • 1,748
  • 1
  • 7
  • 21
0

Lets start with the fact that you are not trying to iterate over a dictionary but to create a list containing dictionary entries from a CSV format string. secondly there are a lot of python syntactic mistakes and errors in your code. Refrain from using reserved word such as "dict" as parameter names.

You can use this code snippet as a start if it helps you but I recommend brushing up on python syntax and best practices.

result = []
for line in csv.splitlines():
    vorname, nachname, email = line.split(",")
    result.append(
        {"vorname": vorname.strip(), "nachname": nachname.strip(), "email": email.strip()})

This can be done also using list comprehension, but is much less readable

NirO
  • 216
  • 2
  • 12