logo
down
shadow

how to prevent a for loop from overwriting a dictionary?


how to prevent a for loop from overwriting a dictionary?

Content Index :

how to prevent a for loop from overwriting a dictionary?
Tag : python , By : Derek
Date : January 11 2021, 05:14 PM

may help you . I am creating a dictionary for a JSON file, through the use of a for loop. However my for loop overwrites the entries
new_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
x = zip(name, hobbies, age)
for n,h,a in x:
    new_dict[n]={'hobbies': h, 'age': a}

print(new_dict) 
third_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]

for i in range(len(name)):
    second_dict={}
    second_dict["hobbies"]=hobbies[i]
    second_dict["age"]=age[i]

    third_dict[name[i]]=second_dict
print(third_dict)

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

PHP prevent foreach loop from overwriting object


Tag : php , By : Guy Kastenbaum
Date : March 29 2020, 07:55 AM
will help you The reason for the "overwriting" is $tempChild = $child;.
That will not deep copy the contents of $child but make both $tempChild and $child point towards the same data structure, which obviously isn't desirable in this case.
$tempChild = clone $child;

Why is this dictionary overwriting itself during for loop?


Tag : python-2.7 , By : Steve M
Date : March 29 2020, 07:55 AM
This might help you If you notice in your code, in the second for loop you have filtered_dict[date_key] = {}. This resets the value of filtered_dict[date_key] instead of allowing you to add to it.
input_dict = function_to_get_input_dict()
filtered_dict = {}
for metric in input_dict['data']:
    for day in metric['values']:
        parsed_date = parser.parse(day['end_time'])
        date_key = parsed_date.strftime('%m/%d/%Y')
        filtered_dict[date_key] = {}
        filtered_dict[date_key]['Total %s' % metric['title']] = 0
        for k, v in day['value'].iteritems():
            filtered_dict[date_key]['%s : %s' % (metric['title'], k)] = v
            filtered_dict[date_key]['Total %s' % metric['title']] += v
pprint(filtered_dict) #debug

How Do you prevent overwriting of data in a Dictionary through a for loop


Tag : python , By : Dave M
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , There are two places you have issues (as the other answer also indicates) -
for domain in dDomainSeqSum.keys():# CHANGE TO COMPRESS FILE
    dDomainSeqSumSWS[domain]={}
    for pdb in dDomainSeqSum[domain]:#add sws of a pdb in a variable and later add that variable to the domain thing
        pdb2 = pdb[:4] #you do not need to convert to list for indexing and you can slice the first four characters off.
        dDomainSeqSumSWS[domain][pdb2]=[]
        for i in range(len(PDBSum)): #make pdb3 search and then compare to the pdb stored
            if pdb in PDBSum[i]:
                if "SWS_ID" in PDBSum[i]:
                    line = PDBSum[i].split()
                    dDomainSeqSumSWS[domain].setdefault(pdb2,[]).append(line[2])

Prevent Python For Loop from overwriting dictionary


Tag : python , By : nobodyzzz
Date : March 29 2020, 07:55 AM
will be helpful for those in need index in int_index = "int_index " + str(index + 1) will always be the same value as after first loop it's value is constant. Hence data is being overwritten.
...

# PART 2 - ANALYSE THE DATA
intersections = {}
index = 0

for a, b in combinations(zones.values(), 2):
  a_geom = a['location']
  b_geom = b['location']
  if a_geom.intersects(b_geom) == True:
    int_index = "int_index " + str(index + 1)
    int_geometry = a_geom.intersection(b_geom)
    int_area = round((a_geom.intersection(b_geom).area),2)
    int_perimeter = round((a_geom.intersection(b_geom).length),2)
    intersections[int_index] = {
      'geometry' : int_geometry,
      'attributes' : {
        'area' : int_area,
        'perimeter' : int_perimeter,
      }
    }
    index += 1

pprint(intersections)

For loop is overwriting dictionary values in list


Tag : python , By : besn
Date : March 29 2020, 07:55 AM
seems to work fine Try this code. Each device was trying to edit the same copy of a dictionary.
listofdevices = []

def begin():
    with open("outputfromterminal", 'r') as f:
        contents = f.read().split(',')[1:]

    for line in contents:
        # do some text stripping
        line = line.split(' ')

        device =  { 'ip': line[0],
                    'mac': line[1],
                    'username': 'admin',
                    'password': [],
                    'device type': '',
                   }

        listofdevices.append(device)
Related Posts Related QUESTIONS :
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • Display image of 2D Sinewaves in 3D
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • Detect if user has clicked the 'maximized' button
  • Does flask_login automatically set the "next" argument?
  • Indents in python 3
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com