Need Help!!

68 views
Skip to first unread message

Dev Pratap Singh

unread,
Jun 25, 2017, 1:57:26 PM6/25/17
to Python GCU Forum
Hello !! I  Have a Dictionary having a key [URL] I want to append multiple values in same key from a file  ?
I m using append function to do it , but  it say " dictionary does not support append function", although  file also contain same url (values) and I want to filter my dictionary too.
Confused with the use of loop with dictionary....

Blithe Brandon

unread,
Jun 25, 2017, 4:23:33 PM6/25/17
to Python GCU Forum
Hi Dev,

You can append to lists, but not dictionary values. Since you didn't share your code, I can only assume that one issue you are having is how you are trying to update the dict values. 

If your dict key points to a list (as you described), you should be able to append by using dict_name[url_example_a].append(new_val). But you're getting an error, so I'm assuming your dictionary doesn't hold lists, or perhaps not just lists.

For example, assume we have dictionary d with three key/value pairs

d = {'url_a': 82344, 'url_b': [1, 2], 'url_c': dict_of_vals}

The keys in this example point to three different data types.

url_a points to an int, url_b points to a list, and url_c points to a dictionary.

Based on your error message, I think you have a dictionary in your dictionary. On the surface, that sounds too complex and without seeing your code, I'd suggest against it.

To add a value to url_a, you need to build a list and assign it to url_a, because you are changing the type of data held by url_a from an int to a list.

Let's add 737 to url_a

val_list = d[url_a]    # val_list is now [82344]
val_list.append(737)  # and now it's [82344, 737]
d[url_a] = val_list

To add 737 to url_b is simpler, because url_b points to a list already.

d[url_b].append(737)  # url_b now points to a list [1, 2, 737]

To add 737 to your dictionary pointed to by url_c, you'd have to access the dictionary, then it's key, then it's value and then append your new value.

You also mention filtering and looping, if you share your code in the future you might get more help.

Blithe

Message has been deleted

huan...@mail.huji.ac.il

unread,
Jun 25, 2017, 5:27:11 PM6/25/17
to Python GCU Forum
Hi Dev,

If you want to append multiple values to the same key in your dictionary by reading those values from a file, one possible way might like following.

filename = "YOUR_FILE_NAME"
with open(filename, 'r') as f:
    dict = {}
    for line in f:
        dict.setdefault("url", []).append(line)

Then, you can print the dict and see the result.

Best wishes, 
Huan
.
Reply all
Reply to author
Forward
0 new messages