Skip to content
Learn Netverks
0

Full Str not Added to Dictionary in Loop

asked 7 hours ago by @qa-v5qjp4sqt10hr32iehap 0 rep · 46 views

python python 3.x

I am running into an issue where my dictionary is not picking up full strings attached to variables, but instead just the first letter. I made a small example of what happens, but I would be happy to attach my full/real code if that would be helpful.


import numpy as np 
import random

trials = 5

d = {'trial': np.empty([trials]),
     'fruit': np.empty([trials], dtype = str),
     'vegetable': np.empty([trials], dtype = str)}

fruits = ['apple', 'orange', 'banana']
vegetables = ['carrot', 'squash', 'sprout']

for i in range(trials): 
    fruit = random.choice(fruits)
    vegetable = random.choice(vegetables)

    # trial data 
    d['trial'][i] = i
    d['fruit'][i] = fruit
    d['vegetable'][i] = vegetable
    print(d)

Like in my real experiment, this code just takes the first letter of the fruit/vegetable to add to my dictionary. This is messing with me, as I need to record ‘lvf’ and ‘lower’ in terms of visual fields in my real experiment, but they both appear as ‘l’ in my dictionary.

I feel the solution may be simple, I just can’t seem to find it anywhere. I have tried adding ‘list()’ around my variables, but that didn’t help. For example:

fruit = random.choice(list(fruits))

If anyone has insight to this issue, I would greatly appreciate it! Thank you all for your help!

Comments on this question (0)

Use comments to ask for clarification — answers go in the answer box below.

Log in to comment on this question.

1

Accepted answer

Look at d after it is declared:

{'trial': array([0., 1., 2., 3., 4.]), 'fruit': array(['', '', '', '', ''], dtype='<U1'), 'vegetable': array(['', '', '', '', ''], dtype='<U1')}

The dtype generated by dtype=str is '<U1'. That's a length 1 little-endian Unicode string.

Decide on a maximum string length and use dtype='<U20' or the like instead and it will work.

Or, in this simple case, just use Python lists:

import random

trials = 5

d = {'trial': [], 'fruit': [], 'vegetable': []}
fruits = ['apple', 'orange', 'banana']
vegetables = ['carrot', 'squash', 'sprout']

for i in range(trials): 
    d['trial'].append(i)
    d['fruit'].append(random.choice(fruits))
    d['vegetable'].append(random.choice(vegetables))

print(d)

Output:

{'trial': [0, 1, 2, 3, 4], 'fruit': ['banana', 'orange', 'banana', 'orange', 'banana'], 'vegetable': ['sprout', 'squash', 'sprout', 'sprout', 'carrot']}

Alex Cole · 0 rep · 7 hours ago

Your answer