[Py2to3] Replace iteritems and itervalues

* Replace the use of iteritems() and itervalues() on dictionary objects
   with items() and values() respectively for Python 3 compatibility.
This commit is contained in:
Andrew Resch 2016-10-16 18:48:48 -07:00 committed by Calum Lind
parent 8b50f3cdbd
commit 7ad8a3cbb5
21 changed files with 40 additions and 40 deletions

View File

@ -125,7 +125,7 @@ class Config(object):
self._save_timer = None self._save_timer = None
if defaults: if defaults:
for key, value in defaults.iteritems(): for key, value in defaults.items():
self.set_item(key, value) self.set_item(key, value)
# Load the config from file in the config_dir # Load the config from file in the config_dir
@ -363,7 +363,7 @@ what is currently in the config and it could not convert the value
""" """
log.debug("Calling all set functions..") log.debug("Calling all set functions..")
for key, value in self.__set_functions.iteritems(): for key, value in self.__set_functions.items():
for func in value: for func in value:
func(key, self.__config[key]) func(key, self.__config[key])

View File

@ -29,7 +29,7 @@ AUTH_LEVELS_MAPPING = {
} }
AUTH_LEVELS_MAPPING_REVERSE = {} AUTH_LEVELS_MAPPING_REVERSE = {}
for key, value in AUTH_LEVELS_MAPPING.iteritems(): for key, value in AUTH_LEVELS_MAPPING.items():
AUTH_LEVELS_MAPPING_REVERSE[value] = key AUTH_LEVELS_MAPPING_REVERSE[value] = key

View File

@ -173,7 +173,7 @@ class FilterManager(component.Component):
# Leftover filter arguments, default filter on status fields. # Leftover filter arguments, default filter on status fields.
for torrent_id in list(torrent_ids): for torrent_id in list(torrent_ids):
status = self.core.create_torrent_status(torrent_id, torrent_keys, plugin_keys) status = self.core.create_torrent_status(torrent_id, torrent_keys, plugin_keys)
for field, values in filter_dict.iteritems(): for field, values in filter_dict.items():
if field in status and status[field] in values: if field in status and status[field] in values:
continue continue
elif torrent_id in torrent_ids: elif torrent_id in torrent_ids:
@ -212,7 +212,7 @@ class FilterManager(component.Component):
# Return a dict of tuples: # Return a dict of tuples:
sorted_items = {} sorted_items = {}
for field in tree_keys: for field in tree_keys:
sorted_items[field] = sorted(items[field].iteritems()) sorted_items[field] = sorted(items[field].items())
if "state" in tree_keys: if "state" in tree_keys:
sorted_items["state"].sort(self._sort_state_items) sorted_items["state"].sort(self._sort_state_items)

View File

@ -160,7 +160,7 @@ class TorrentOptions(dict):
"super_seeding": "super_seeding", "super_seeding": "super_seeding",
"priority": "priority", "priority": "priority",
} }
for opt_k, conf_k in options_conf_map.iteritems(): for opt_k, conf_k in options_conf_map.items():
self[opt_k] = config[conf_k] self[opt_k] = config[conf_k]
self["file_priorities"] = [] self["file_priorities"] = []
self["mapped_files"] = {} self["mapped_files"] = {}
@ -1323,7 +1323,7 @@ class Torrent(object):
torrent.waiting_on_folder_rename = [_dir for _dir in torrent.waiting_on_folder_rename if _dir] torrent.waiting_on_folder_rename = [_dir for _dir in torrent.waiting_on_folder_rename if _dir]
component.get("TorrentManager").save_resume_data((self.torrent_id,)) component.get("TorrentManager").save_resume_data((self.torrent_id,))
d = DeferredList(wait_on_folder.values()) d = DeferredList(list(wait_on_folder.values()))
d.addBoth(on_folder_rename_complete, self, folder, new_folder) d.addBoth(on_folder_rename_complete, self, folder, new_folder)
return d return d

View File

@ -746,7 +746,7 @@ class TorrentManager(component.Component):
""" """
if torrent_ids is None: if torrent_ids is None:
torrent_ids = (t[0] for t in self.torrents.iteritems() if t[1].handle.need_save_resume_data()) torrent_ids = (t[0] for t in self.torrents.items() if t[1].handle.need_save_resume_data())
def on_torrent_resume_save(dummy_result, torrent_id): def on_torrent_resume_save(dummy_result, torrent_id):
"""Recieved torrent resume_data alert so remove from waiting list""" """Recieved torrent resume_data alert so remove from waiting list"""
@ -918,7 +918,7 @@ class TorrentManager(component.Component):
def cleanup_torrents_prev_status(self): def cleanup_torrents_prev_status(self):
"""Run cleanup_prev_status for each registered torrent""" """Run cleanup_prev_status for each registered torrent"""
for torrent in self.torrents.iteritems(): for torrent in self.torrents.items():
torrent[1].cleanup_prev_status() torrent[1].cleanup_prev_status()
def on_set_max_connections_per_torrent(self, key, value): def on_set_max_connections_per_torrent(self, key, value):

View File

@ -99,7 +99,7 @@ class Core(CorePluginBase):
def enable_looping(self): def enable_looping(self):
# Enable all looping calls for enabled watchdirs here # Enable all looping calls for enabled watchdirs here
for watchdir_id, watchdir in self.watchdirs.iteritems(): for watchdir_id, watchdir in self.watchdirs.items():
if watchdir["enabled"]: if watchdir["enabled"]:
self.enable_watchdir(watchdir_id) self.enable_watchdir(watchdir_id)
@ -108,7 +108,7 @@ class Core(CorePluginBase):
component.get("EventManager").deregister_event_handler( component.get("EventManager").deregister_event_handler(
"PreTorrentRemovedEvent", self.__on_pre_torrent_removed "PreTorrentRemovedEvent", self.__on_pre_torrent_removed
) )
for loopingcall in self.update_timers.itervalues(): for loopingcall in self.update_timers.values():
loopingcall.stop() loopingcall.stop()
self.config.save() self.config.save()
@ -128,7 +128,7 @@ class Core(CorePluginBase):
check_input( check_input(
os.path.isdir(options["abspath"]), _("Path does not exist.") os.path.isdir(options["abspath"]), _("Path does not exist.")
) )
for w_id, w in self.watchdirs.iteritems(): for w_id, w in self.watchdirs.items():
if options["abspath"] == w["abspath"] and watchdir_id != w_id: if options["abspath"] == w["abspath"] and watchdir_id != w_id:
raise Exception("Path is already being watched.") raise Exception("Path is already being watched.")
for key in options: for key in options:
@ -223,7 +223,7 @@ class Core(CorePluginBase):
watchdir["stop_ratio_toggle"] = watchdir["stop_at_ratio_toggle"] watchdir["stop_ratio_toggle"] = watchdir["stop_at_ratio_toggle"]
# We default to True when reading _toggle values, so a config # We default to True when reading _toggle values, so a config
# without them is valid, and applies all its settings. # without them is valid, and applies all its settings.
for option, value in watchdir.iteritems(): for option, value in watchdir.items():
if OPTIONS_AVAILABLE.get(option): if OPTIONS_AVAILABLE.get(option):
if watchdir.get(option + "_toggle", True) or option in ["owner", "seed_mode"]: if watchdir.get(option + "_toggle", True) or option in ["owner", "seed_mode"]:
opts[option] = value opts[option] = value
@ -381,7 +381,7 @@ class Core(CorePluginBase):
return self.watchdirs return self.watchdirs
watchdirs = {} watchdirs = {}
for watchdir_id, watchdir in self.watchdirs.iteritems(): for watchdir_id, watchdir in self.watchdirs.items():
if watchdir.get("owner", "localclient") == session_user: if watchdir.get("owner", "localclient") == session_user:
watchdirs[watchdir_id] = watchdir watchdirs[watchdir_id] = watchdir
@ -409,7 +409,7 @@ class Core(CorePluginBase):
os.access(abswatchdir, os.R_OK | os.W_OK), os.access(abswatchdir, os.R_OK | os.W_OK),
"You must have read and write access to watch folder." "You must have read and write access to watch folder."
) )
if abswatchdir in [wd["abspath"] for wd in self.watchdirs.itervalues()]: if abswatchdir in [wd["abspath"] for wd in self.watchdirs.values()]:
raise Exception("Path is already being watched.") raise Exception("Path is already being watched.")
options.setdefault("enabled", False) options.setdefault("enabled", False)
options["abspath"] = abswatchdir options["abspath"] = abswatchdir
@ -447,7 +447,7 @@ class Core(CorePluginBase):
torrent_id) torrent_id)
return return
torrent_fname = torrent.filename torrent_fname = torrent.filename
for watchdir in self.watchdirs.itervalues(): for watchdir in self.watchdirs.values():
if not watchdir.get("copy_torrent_toggle", False): if not watchdir.get("copy_torrent_toggle", False):
# This watchlist does copy torrents # This watchlist does copy torrents
continue continue

View File

@ -401,7 +401,7 @@ class GtkUI(GtkPluginBase):
def create_model(self): def create_model(self):
store = gtk.ListStore(str, bool, str, str) store = gtk.ListStore(str, bool, str, str)
for watchdir_id, watchdir in self.watchdirs.iteritems(): for watchdir_id, watchdir in self.watchdirs.items():
store.append([ store.append([
watchdir_id, watchdir['enabled'], watchdir_id, watchdir['enabled'],
watchdir.get('owner', 'localclient'), watchdir['path'] watchdir.get('owner', 'localclient'), watchdir['path']
@ -474,7 +474,7 @@ class GtkUI(GtkPluginBase):
def on_apply_prefs(self): def on_apply_prefs(self):
log.debug("applying prefs for AutoAdd") log.debug("applying prefs for AutoAdd")
for watchdir_id, watchdir in self.watchdirs.iteritems(): for watchdir_id, watchdir in self.watchdirs.items():
client.autoadd.set_options(watchdir_id, watchdir) client.autoadd.set_options(watchdir_id, watchdir)
def on_show_prefs(self): def on_show_prefs(self):
@ -488,7 +488,7 @@ class GtkUI(GtkPluginBase):
log.trace("Got whatchdirs from core: %s", watchdirs) log.trace("Got whatchdirs from core: %s", watchdirs)
self.watchdirs = watchdirs or {} self.watchdirs = watchdirs or {}
self.store.clear() self.store.clear()
for watchdir_id, watchdir in self.watchdirs.iteritems(): for watchdir_id, watchdir in self.watchdirs.items():
self.store.append([ self.store.append([
watchdir_id, watchdir['enabled'], watchdir_id, watchdir['enabled'],
watchdir.get('owner', 'localclient'), watchdir['path'] watchdir.get('owner', 'localclient'), watchdir['path']

View File

@ -133,7 +133,7 @@ class Core(CorePluginBase):
def disable(self): def disable(self):
self.config.save() self.config.save()
event_manager = component.get("EventManager") event_manager = component.get("EventManager")
for event, handler in self.registered_events.iteritems(): for event, handler in self.registered_events.items():
event_manager.deregister_event_handler(event, handler) event_manager.deregister_event_handler(event, handler)
log.debug("Execute core plugin disabled!") log.debug("Execute core plugin disabled!")

View File

@ -118,7 +118,7 @@ class Core(CorePluginBase):
log.debug("post_torrent_add") log.debug("post_torrent_add")
torrent = self.torrents[torrent_id] torrent = self.torrents[torrent_id]
for label_id, options in self.labels.iteritems(): for label_id, options in self.labels.items():
if options["auto_add"]: if options["auto_add"]:
if self._has_auto_match(torrent, options): if self._has_auto_match(torrent, options):
self.set_torrent(torrent_id, label_id) self.set_torrent(torrent_id, label_id)
@ -132,7 +132,7 @@ class Core(CorePluginBase):
# Utils # # Utils #
def clean_config(self): def clean_config(self):
"""remove invalid data from config-file""" """remove invalid data from config-file"""
for torrent_id, label_id in list(self.torrent_labels.iteritems()): for torrent_id, label_id in list(self.torrent_labels.items()):
if (label_id not in self.labels) or (torrent_id not in self.torrents): if (label_id not in self.labels) or (torrent_id not in self.torrents):
log.debug("label: rm %s:%s", torrent_id, label_id) log.debug("label: rm %s:%s", torrent_id, label_id)
del self.torrent_labels[torrent_id] del self.torrent_labels[torrent_id]
@ -266,14 +266,14 @@ class Core(CorePluginBase):
self.labels[label_id].update(options_dict) self.labels[label_id].update(options_dict)
# apply # apply
for torrent_id, label in self.torrent_labels.iteritems(): for torrent_id, label in self.torrent_labels.items():
if label_id == label and torrent_id in self.torrents: if label_id == label and torrent_id in self.torrents:
self._set_torrent_options(torrent_id, label_id) self._set_torrent_options(torrent_id, label_id)
# auto add # auto add
options = self.labels[label_id] options = self.labels[label_id]
if options["auto_add"]: if options["auto_add"]:
for torrent_id, torrent in self.torrents.iteritems(): for torrent_id, torrent in self.torrents.items():
if self._has_auto_match(torrent, options): if self._has_auto_match(torrent, options):
self.set_torrent(torrent_id, label_id) self.set_torrent(torrent_id, label_id)

View File

@ -136,7 +136,7 @@ class Core(CorePluginBase):
# extract the ones we are interested in # extract the ones we are interested in
# adding them to the 1s array # adding them to the 1s array
for stat, stat_list in self.stats[1].iteritems(): for stat, stat_list in self.stats[1].items():
if stat in stats: if stat in stats:
stat_list.insert(0, int(stats[stat])) stat_list.insert(0, int(stats[stat]))
else: else:
@ -150,7 +150,7 @@ class Core(CorePluginBase):
self.last_update[interval] = update_time self.last_update[interval] = update_time
self.count[interval] = 0 self.count[interval] = 0
current_stats = self.stats[interval] current_stats = self.stats[interval]
for stat, stat_list in self.stats[base].iteritems(): for stat, stat_list in self.stats[base].items():
try: try:
avg = mean(stat_list[0:multiplier]) avg = mean(stat_list[0:multiplier])
except ValueError: except ValueError:

View File

@ -242,7 +242,7 @@ class Graph(object):
self.draw_y_text(y_tick_text[i], left, y) self.draw_y_text(y_tick_text[i], left, y)
self.draw_line(gray, left, top, left, bottom) self.draw_line(gray, left, top, left, bottom)
for stat, info in stats.iteritems(): for stat, info in stats.items():
if len(info['values']) > 0: if len(info['values']) > 0:
self.draw_value_poly(info['values'], info['color'], max_value, bounds) self.draw_value_poly(info['values'], info['color'], max_value, bounds)
self.draw_value_poly(info['values'], info['fill_color'], max_value, bounds, info['fill']) self.draw_value_poly(info['values'], info['fill_color'], max_value, bounds, info['fill'])

View File

@ -18,7 +18,7 @@ from deluge.ui.client import client
def print_totals(totals): def print_totals(totals):
for name, value in totals.iteritems(): for name, value in totals.items():
print(name, fsize(value)) print(name, fsize(value))
print("overhead:") print("overhead:")

View File

@ -300,7 +300,7 @@ class AddTorrentDialog(component.Component):
def add_files(self, parent_iter, split_files): def add_files(self, parent_iter, split_files):
ret = 0 ret = 0
for key, value in split_files.iteritems(): for key, value in split_files.items():
if key.endswith(os.path.sep): if key.endswith(os.path.sep):
chunk_iter = self.files_treestore.append( chunk_iter = self.files_treestore.append(
parent_iter, [True, key, 0, -1, False, gtk.STOCK_DIRECTORY]) parent_iter, [True, key, 0, -1, False, gtk.STOCK_DIRECTORY])

View File

@ -362,7 +362,7 @@ class FilesTab(Tab):
def add_files(self, parent_iter, split_files): def add_files(self, parent_iter, split_files):
chunk_size_total = 0 chunk_size_total = 0
for key, value in split_files.iteritems(): for key, value in split_files.items():
if key.endswith("/"): if key.endswith("/"):
chunk_iter = self.treestore.append(parent_iter, chunk_iter = self.treestore.append(parent_iter,
[key, 0, "", 0, 0, -1, gtk.STOCK_DIRECTORY]) [key, 0, "", 0, 0, -1, gtk.STOCK_DIRECTORY])

View File

@ -159,7 +159,7 @@ class FilterTreeView(component.Component):
# update rows # update rows
visible_filters = [] visible_filters = []
for cat, filters in filter_items.iteritems(): for cat, filters in filter_items.items():
for value, count in filters: for value, count in filters:
self.update_row(cat, value, count) self.update_row(cat, value, count)
visible_filters.append((cat, value)) visible_filters.append((cat, value))

View File

@ -118,7 +118,7 @@ class ListView(object):
def set_col_attributes(self, renderer, add=True, **kw): def set_col_attributes(self, renderer, add=True, **kw):
if add is True: if add is True:
for attr, value in kw.iteritems(): for attr, value in kw.items():
self.add_attribute(renderer, attr, value) self.add_attribute(renderer, attr, value)
else: else:
self.set_attributes(renderer, **kw) self.set_attributes(renderer, **kw)

View File

@ -41,7 +41,7 @@ class _GtkBuilderSignalsHolder(object):
def connect_signals(self, mapping_or_class): def connect_signals(self, mapping_or_class):
if isinstance(mapping_or_class, dict): if isinstance(mapping_or_class, dict):
for name, handler in mapping_or_class.iteritems(): for name, handler in mapping_or_class.items():
if hasattr(self, name): if hasattr(self, name):
raise RuntimeError( raise RuntimeError(
"A handler for signal %r has already been registered: %s" % "A handler for signal %r has already been registered: %s" %

View File

@ -496,7 +496,7 @@ class MenuBar(component.Component):
known_accounts_to_log = [] known_accounts_to_log = []
for account in known_accounts: for account in known_accounts:
account_to_log = {} account_to_log = {}
for key, value in account.copy().iteritems(): for key, value in account.copy().items():
if key == 'password': if key == 'password':
value = '*' * len(value) value = '*' * len(value)
account_to_log[key] = value account_to_log[key] = value
@ -539,7 +539,7 @@ class MenuBar(component.Component):
return return
torrent_owner = component.get("TorrentView").get_torrent_status(selected[0])["owner"] torrent_owner = component.get("TorrentView").get_torrent_status(selected[0])["owner"]
for username, item in self.change_owner_submenu_items.iteritems(): for username, item in self.change_owner_submenu_items.items():
item.set_active(username == torrent_owner) item.set_active(username == torrent_owner)
def _on_change_owner_toggled(self, widget, username): def _on_change_owner_toggled(self, widget, username):

View File

@ -1006,7 +1006,7 @@ class Preferences(component.Component):
known_accounts_to_log = [] known_accounts_to_log = []
for account in known_accounts: for account in known_accounts:
account_to_log = {} account_to_log = {}
for key, value in account.copy().iteritems(): for key, value in account.copy().items():
if key == 'password': if key == 'password':
value = '*' * len(value) value = '*' * len(value)
account_to_log[key] = value account_to_log[key] = value

View File

@ -129,7 +129,7 @@ class TorrentDetails(component.Component):
# We need to rename the tab in the state for backwards compat # We need to rename the tab in the state for backwards compat
self.state = [(tab_name.replace("Statistics", "Status"), visible) for tab_name, visible in state] self.state = [(tab_name.replace("Statistics", "Status"), visible) for tab_name, visible in state]
for tab in default_tabs.itervalues(): for tab in default_tabs.values():
self.add_tab(tab(), generate_menu=False) self.add_tab(tab(), generate_menu=False)
# Generate the checklist menu # Generate the checklist menu
@ -140,7 +140,7 @@ class TorrentDetails(component.Component):
# Determine insert position based on weight # Determine insert position based on weight
# weights is a list of visible tab names in weight order # weights is a list of visible tab names in weight order
weights = sorted([(tab.weight, name) for name, tab in self.tabs.iteritems() if tab.is_visible]) weights = sorted([(tab.weight, name) for name, tab in self.tabs.items() if tab.is_visible])
log.debug("weights: %s", weights) log.debug("weights: %s", weights)
log.debug("weight of tab: %s", weight) log.debug("weight of tab: %s", weight)
@ -243,7 +243,7 @@ class TorrentDetails(component.Component):
self.generate_menu() self.generate_menu()
show = False show = False
for name, tab in self.tabs.iteritems(): for name, tab in self.tabs.items():
show = show or tab.is_visible show = show or tab.is_visible
self.visible(show) self.visible(show)

View File

@ -178,7 +178,7 @@ class SessionProxy(component.Component):
def on_status(result, torrent_ids, keys): def on_status(result, torrent_ids, keys):
# Update the internal torrent status dict with the update values # Update the internal torrent status dict with the update values
t = time() t = time()
for key, value in result.iteritems(): for key, value in result.items():
try: try:
self.torrents[key][0] = t self.torrents[key][0] = t
self.torrents[key][1].update(value) self.torrents[key][1].update(value)