How to add index to a list inside a dictionary

python dictionary with list as value
python dictionary index()
python list of dictionaries
python convert list to dictionary with index
dictionary inside list python
python dictionary index of key
python index of dictionary in list
add to dictionary python

I have a dictionary here:

dict = {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3']}

What is the necessary process to get the following result?

dict = {'A':['1_01','1_02','1_03','1_04','1_05'], 'B':['2_01','2_02'], 'C':['3_01','3_02','3_03','3_04']}

I have been learning python for quite a while now but dictionary is kind of new to me.

As others mentioned, refrain from using built-in keywords as variable names, such as dict. I kept it for simplicity on your part.

This is probably the most pythonic way of doing it (one line of code):

dict = {key:[x+"_0"+str(cnt+1) for cnt,x in enumerate(value)] for key,value in dict.items()}

You could also iterate through each dictionary item, and then each list item and manually change the list names as shown below:

for key,value in dict.items():
    for cnt,x in enumerate(value):
        dict[key][cnt] = x+"_0"+str(cnt+1)

Also, as some others have mentioned, if you want numbers greater than 10 to save as 1_10 rather than 1_010 you can you an if/else statement inside of the list comprehension...

dict = {key:[x+"_0"+str(cnt+1) if cnt+1 < 10 else x+"_"+str(cnt+1) for cnt,x in enumerate(value)] for key,value in dict.items()}

Python, Method #2: Adding nested list as value using append() method. Create a new list and we can simply append that list to the value. To download the source code, you can visit the Generic List and Dictionary in C# Source Code. We are going to split this article into the following sections: List<T> Methods and Properties; Dictionary; Methods and Properties; List<T> A List<T> represents a strongly typed collection of objects that can be accessed by index.

Use enumerate to iterate over list keeping track of index:

d = {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3']}

newd = {}
for k, v in d.items():
    newd[k] = [f'{x}_0{i}' for i, x in enumerate(v, 1)]

print(newd)

Also a dictionary-comprehension:

d = {k: [f'{x}_0{i}' for i, x in enumerate(v, 1)] for k, v in d.items()}

Note: Don't name your dictionary as dict because it shadows the built-in.

Python, This article deals with yet another similar type problem of converting a list to dictionary, with values as the index where element occurs. Let's discuss certain� Examples. The following code example creates an empty Dictionary<TKey,TValue> of strings with string keys and uses the Add method to add some elements. The example demonstrates that the Add method throws an ArgumentException when attempting to add a duplicate key.

d= {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3']}

{x:[j + '_'+ '{:02}'.format(i+1) for i,j in enumerate(y)] for x,y in d.items()}

Python Dictionaries with Python, The Python Dictionary object provides a key:value indexing facility. dictionary are indexed by keys, they are not held in any particular order, unlike a list To add a value to a Dictionary, specify the new key and set a value. values that can be added to a dictionary (within the bounds of physical memory). This will create a new list object, if the key is not found in the dictionary. Note: Since the defaultdict will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.

First iterate on keys.

Then loop on keys you are getting on key like for 'A' value is ['1','1','1','1','1'] then we can change the element at ['1','1','1','1','1']

enumerate() helps you iterate on index,value then index starts with zero as per your expected output add 1 to index. As you want the trailing 0 before each count we did '%02d'% (index+1)

Like this:

dict = {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3']}


for i in dict.keys(): #iterate on keys
    for index,val in enumerate(dict[i]): #took value as we have key in i
        element='%02d'% (index+1) #add trailing 0 we converted 1 to int 01
        dict[i][index]=val+"_"+ str(element) #assign new value with converting integer to string

print(dict)

Output:

{'A': ['1_01', '1_02', '1_03', '1_04', '1_05'], 'C': ['3_01', '3_02', '3_03', '3_04'], 'B': ['2_01', '2_02']}

Lists, Tuples and Dictionaries - codebar, Lists and dictionaries are very common in Python and are structures you can Indexes. The primary trait of lists is that they're sorted. This means that if you ask a cover here is that there's nothing stopping you from putting a list inside a list. Then, we add the key:value pair i.e people[3]['Name'] = 'Luna' inside the dictionary 3. Similarly, we do this for key age, sex and married one by one. When we print the people[3], we get key:value pairs of dictionary 3. Example 4: Add another dictionary to the nested dictionary

adict = {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3'], 'D': '23454'}

newdict = {}
for i,v in adict.items():
    if isinstance(v, list):
        count = 0
        for e in v:
            count += 1
            e += '_0' + str(count)
            newdict[i] = newdict.get(i, [e]) + [e]
    else:
        newdict[i] = newdict.get(i, v)

print (newdict)
#{'A': ['1_01', '1_01', '1_02', '1_03', '1_04', '1_05'], 'B': ['2_01', '2_01', '2_02'], 'C': ['3_01', '3_01', '3_02', '3_03', '3_04'], 'D': '23454'}

This solution will check for whether your value in the dictionary is a list before assigning an index to it

Manipulating Lists and Dictionaries in Python, Before we dive into our discussion about lists and dictionaries in Python, Of course, we can add that key and its corresponding value as a new element to To access any of the list elements, we can use its index: Particularly, lists of dictionaries are what JSON (Javascript Object Notation) is made of. actually I found a novel solution that really helped me out, If you are especially concerned with the index of a certain value in a list or data set, you can just set the value of dictionary to that Index!:

20. Dictionaries — How to Think Like a Computer Scientist: Learning , All of the compound data types we have studied in detail so far — strings, lists, and which use integers as indices to access the values they contain within them. One way to create a dictionary is to start with the empty dictionary and add� I'm trying to put values into a dictionary dependent on the key For example, if in a list of keys at the index 0 there is a letter "a". I want to add the val with index 0 to a list inside of a dictionary with the key "a" ( dictionary (key is "a" at index 0 , val at index 0) dictionary (key is "b" at index 2 , val at index 2))

How to index a dictionary in Python, Call list(*args) with a dictionary as *args to return a list of the keys. Use the indexing syntax list[index] to return the key at index in list . a_dictionary = {"a": 1, " b": 2}. Examples. The following example demonstrates how to add, remove, and insert a simple business object in a List<T>.. using System; using System.Collections.Generic; // Simple business object.

Python Nested Dictionary (With Examples), In the above program, we create an empty dictionary 3 inside the dictionary people . Then, we add the key:value pair i.e people[3]['Name'� Python add elements to List Examples. We can add an element to the end of the list or at any given index. There are ways to add elements from an iterable to the list. We can also use + operator to concatenate multiple lists to create a new list. 1. append() This function add the element to the end of the list.

Comments
  • Treat dict as just another data type similar to list where you can give names to the indexes. {"key": "value"} is the general format for this data type where key acts as index. To iterate through dictionary you use for key, value in dict_name.items():. You should also look into docs of pythons on dictionary.
  • While this is simple to do the result might be less helpful from data model perspective.
  • What do you want to get when count of items over 10, got '1-010' or just '1-10'?
  • N.B. Since dict is a built-in type, you may want to use another name for your variable. :-)
  • This is the clearest answer! Thank you for your help!
  • Glad I could help! :)
  • Mark this as answered if this solved your problem so that others can find it easily!!
  • what if count of items over 10, got '1-010'?
  • @jiaJimmy, Yes. (assuming that's what OP wants).
  • To help learning, please spend some time explaining your answer. How and why does it solve OP's problem?